1

嘿伙计们,我正在尝试创建一个循环,直到用户输入正确的字符选择。当我输入错误的选择时,我收到错误 java.lang.NullPointerException。这可能与我输入的方式有关,但如果我不需要,我不想改变它。选择是类的私有成员。

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
4

3 回答 3

1

检查 input.findInLine(".") 以查看它是否为空。如果您没有预期的输入,它将不会返回任何内容..

于 2015-10-11T17:14:49.700 回答
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
于 2015-10-11T17:23:30.237 回答
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
于 2015-10-11T17:24:30.490 回答