嘿伙计我试图创建一个循环,直到用户输入正确的字符选择。当我输入错误的选择时,我得到错误java.lang.NullPointerException。它可能与我输入的方式有关,但如果我不必,我不想改变它。 choice是该类的私有成员。
char wf() {
Scanner input = new Scanner(System.in);
System.out.println("What is your choice? (x/o)");
choice = input.findInLine(".").charAt(0);
while (choice != 'x' && choice != 'o') {
System.out.println("You must enter x or o!");
choice = input.findInLine(".").charAt(0);
}
return choice;
}//end wf
答案 0 :(得分:1)
检查input.findInLine(“。”)以查看它是否为null。如果您没有预期的输入,它将不会返回任何内容..
答案 1 :(得分:1)
更改下面的功能(我已经测试过此代码):
char wf() {
Scanner input = new Scanner(System.in);
System.out.println("What is your choice? (x/o)");
char choice = input.findInLine(".").charAt(0);
while (choice != 'x' && choice != 'o') {
System.out.println("You must enter x or o!");
choice = input.next().charAt(0);
}
return choice;
}//end wf
答案 2 :(得分:1)
更改您的代码,如下所示
char wf() {
Scanner input = new Scanner(System.in);
System.out.println("What is your choice? (x/o)");
if(input.findInLine(".") !=null){
choice = input.findInLine(".").charAt(0);
while (choice != 'x' && choice != 'o') {
System.out.println("You must enter x or o!");
choice = input.findInLine(".").charAt(0);
}
}
return choice;
}//end wf