好的家伙所以我试图通过if
... else
子句从3个文件中的1个读入
只是Scanner myScanner = new Scanner(new File("maze1.txt"));
会运行问题,但我希望用户选择他/她想要运行的迷宫
public class Main {
private static Scanner myScanner;
public static void main(String[] args) throws FileNotFoundException {
System.out.println("Please Enter 1,2 or 3 to pick the different maze you would like being solved.");
Scanner myScannerinput = new Scanner(System.in);
int Mazenumber = myScannerinput.nextInt();
if(Mazenumber == 1){
Scanner myScanner = new Scanner(new File("maze1.txt"));
}
else if(Mazenumber == 2){
Scanner myScanner = new Scanner(new File("maze2.txt"));
}
else if(Mazenumber == 3){
Scanner myScanner = new Scanner(new File("maze3.txt"));
}
else{
System.out.println("You did not choose one of the 3 mazes");
}
int numRows = myScanner.nextInt();
int numCols = myScanner.nextInt();
myScanner.nextLine();
int startX = 0;
int startY = 0;'
请输入1,2或3以选择您想要解决的不同迷宫。
Exception in thread "main" java.lang.NullPointerException
at Main.main(Main.java:33)
答案 0 :(得分:1)
不要在if条件中创建单独的新Scanner。在if条件之前创建一个扫描程序,并根据您的偏好分配文件。
int Mazenumber = myScannerinput.nextInt();
Scanner myScanner =null;
if(Mazenumber == 1){
myScanner = new Scanner(new File("maze1.txt"));
}
else if(Mazenumber == 2){
myScanner = new Scanner(new File("maze2.txt"));
}
else if(Mazenumber == 3){
myScanner = new Scanner(new File("maze3.txt"));
}
else{
System.out.println("You did not choose one of the 3 mazes");
}
if(myScanner!=null){
int numRows = myScanner.nextInt();
int numCols = myScanner.nextInt();
myScanner.nextLine();
}
答案 1 :(得分:0)
而不是
int Mazenumber = myScannerinput.nextInt();
if(Mazenumber == 1){
Scanner myScanner = new Scanner(new File("maze1.txt"));
}
else if(Mazenumber == 2){
Scanner myScanner = new Scanner(new File("maze2.txt"));
}
else if(Mazenumber == 3){
Scanner myScanner = new Scanner(new File("maze3.txt"));
}
else{
System.out.println("You did not choose one of the 3 mazes");
}
使用
Scanner myScanner;
int Mazenumber = 0;
do {
System.out.println("Choose 1, 2 or 3");
Mazenumber = myScannerinput.nextInt();
if(Mazenumber >=1 && Mazenumber <=3) {
String fileName = "maze"+Mazenumber+".txt";
myScanner = new Scanner(new File(fileName));
} else {
System.out.println("You did not choose one of the 3 mazes");
}
} while(Mazenumber>3 && Mazenumber <1);
Main.main(Main.java:33)中线程“main”java.lang.NullPointerException中的异常
异常是因为,您已在Scanner myScanner
阻止内声明了if-else
。
答案 2 :(得分:0)
您在if块中定义并初始化myScanner,因此一旦离开它就会超出范围