java.lang.NullPointerException表单用户输入 [英] java.lang.NullPointerException form user input

查看:142
本文介绍了java.lang.NullPointerException表单用户输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个循环,直到用户输入正确的字符选择为止.输入错误的选择时,将显示错误java.lang.NullPointerException.可能是我输入的方式,但是如果不需要的话,我不想更改它.选择是班上的私人成员.

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

推荐答案

按如下所示更改功能(我已经测试过此代码):

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

这篇关于java.lang.NullPointerException表单用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆