验证用户输入的字母

时间:2013-05-12 02:34:16

标签: java string validation

我在这里有我的代码,我正在尝试检查用户是否输入Y或N来获取switch语句,但是即使我写Y或N它给我错误信息,我做错了什么?提前谢谢

public void anotherAction() throws IOException{
    System.out.println();
    System.out.println("Would you like to perform an additional action? 'Y' or 'N'");
    while(!reader.hasNextLine()){
        System.out.println("Enter either 'Y' or 'N'");
    }
    String response =reader.nextLine().toUpperCase();
    while(response != "Y" || response != "N"){
        System.out.println("Enter 'Y' or 'N'");
        response = reader.nextLine();
        continue;
    }
    switch(response){
        case "Y":
            cc.getCommand(this.makeOption());
            break;
        case "N":
            System.out.println("Exiting System...");
            break;
    }
}

2 个答案:

答案 0 :(得分:0)

您应该使用equals()来比较字符串。

答案 1 :(得分:0)

上面的答案是正确的 - 但是你可能希望尽量减少你对主要功能进行的字符串比较(很快就很难维护,并且你有一个很好的机会将用户输入封装为bool)

从长远来看,这样的事情可能对你有所帮助

    public void anotherAction() throws IOException
    {
        System.out.println();
        System.out.println("Would you like to perform an additional action? 'Y' or 'N'");
        if (getAction()) 
        {
            cc.getCommand(this.makeOption());
        }
        else {
            System.out.println("Exiting System...");
        }
    }

    private bool getAction()
    {
        while(true)
        {
            System.out.println("Enter either 'Y' or 'N'");
            String response =reader.nextLine().toUpperCase();
            if (response.equals("Y")) {
                return true;
            }
            else if (response.Equals("N")) {
                return false;
            }
            else {
                System.out.println("Wrong input, please try again...");
            }
        }
    }