java.lang.NullPointerException form user input

為{幸葍}努か 提交于 2019-12-13 02:14:01

问题


Hey guys I'm trying to create a loop until a correct character choice is entered by the user. When I enter a wrong choice I get the error java.lang.NullPointerException. It might be with the way I'm inputing but I don't want to change that if I don't have to. choice is a private member of the 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

回答1:


Change the function as below (I have tested this code):

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:


Check input.findInLine(".") to see if it null. If you don't have the expected input, it won't return anything..




回答3:


change your code like below

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


来源:https://stackoverflow.com/questions/33067801/java-lang-nullpointerexception-form-user-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!