java.lang.NullPointerException 表单用户输入
java.lang.NullPointerException form user input
大家好,我正在尝试创建一个循环,直到用户输入正确的字符选择。当我输入错误的选择时,我得到错误 java.lang.NullPointerException。这可能与我输入的方式有关,但如果不需要,我不想更改它。 choice 是 class 的私有成员。
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(".") 以查看它是否为空。如果您没有预期的输入,它不会 return 任何东西..
修改函数如下(我测试过这段代码):
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
像下面这样更改您的代码
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
大家好,我正在尝试创建一个循环,直到用户输入正确的字符选择。当我输入错误的选择时,我得到错误 java.lang.NullPointerException。这可能与我输入的方式有关,但如果不需要,我不想更改它。 choice 是 class 的私有成员。
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(".") 以查看它是否为空。如果您没有预期的输入,它不会 return 任何东西..
修改函数如下(我测试过这段代码):
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
像下面这样更改您的代码
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