这就是我试图用9999的种子值打印的内容(见链接中的图像)。程序要求用户输入int值,我已经使用getSeed()检查了主类中的错误。另外,忽略输入文件。
public static void main(String[] args) throws IOException{
int seed = getSeed();
Scanner inFile = new Scanner(new FileReader("input.txt"));
while(inFile.hasNext()){
System.out.println(inFile.nextLine());
Board b = new Board(seed);
}
}
Board Class
当我运行程序时,我收到一个空指针错误。另外,我想知道如何正确地转换为char。
谢谢你的真知灼见。
public static int getSeed(){
Scanner sc = new Scanner(System.in);
int userInput;
while(true){
try{
System.out.println("Enter an integer seed value greater than 0: ");
userInput = Integer.parseInt(sc.next());
if( userInput > 0)
return userInput;
}
catch(NumberFormatException e){
System.out.println("Invalid!");
}
}
}
您的板类有几个错误:
-
Board[][]未初始化,因此null指针异常
-
在函数resetBoard()你应该有board[i][j] = randomChar,反之亦然。
3。为了得到一个4*4的板子,循环应该在4处结束。你得到的是一个5*5的数组。
我把这个类重写为:
import java.util.Random;
/**
* Created by derricknyakiba on 07/10/2016.
*/
public class Board {
private char[][] board;
private boolean[][] visited;
private String word;
public Board(int seed){
board = new char[4][4];
Random rand = new Random(seed);
for(int i = 0 ; i < 4 ; i++){
for( int j = 0 ; j < 4 ; j++ ){
char randomChar = (char) (rand.nextInt(27) + 65);
board[i][j] = randomChar; }
}
printBoard();
}
public void printBoard(){
for(int i = 0 ; i < 4 ; i++){
for( int j = 0 ; j < 4 ; j++ ){
System.out.print( board[i][j] + " ");
}
System.out.println();
}
}
}