java.lang.NullPointerException表单用户输入
嘿,伙计们,我正在尝试创建一个循环,直到用户输入正确的字符选择。当我输入错误的选项时,会出现错误java.lang.NullPointerException。这可能与我输入的方式有关,但如果不需要的话,我不想改变。choice是班级的私人成员java.lang.NullPointerException表单用户输入,java,nullpointerexception,java.lang.class,Java,Nullpointerexception,Java.lang.class,嘿,伙计们,我正在尝试创建一个循环,直到用户输入正确的字符选择。当我输入错误的选项时,会出现错误java.lang.NullPointerException。这可能与我输入的方式有关,但如果不需要的话,我不想改变。choice是班级的私人成员 char wf() { Scanner input = new Scanner(System.in); System.out.println("What is your choice? (x/o)"); choice = in
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
检查input.findInLine(“.”),查看它是否为null。如果您没有预期的输入,它将不会返回任何内容。按以下方式更改函数(我已测试了此代码):
像下面这样更改代码
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
findLineAt
是否返回null
?如果是这样的话,那就是问题所在,因为您会在之后立即调用charAt
。如果findLineAt
为null
,您将无法调用方法,因为没有对象可从中调用方法(而是有null),因此NPE。因为findLineAt
返回null
的原因很明显。你可以通过阅读JavaDoc和调试这个方法来了解那里发生了什么。你能解释一下为什么它应该工作,即使它不工作吗?
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