0

我在这里有我的代码,我正在尝试检查用户是否输入 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;
    }
}
4

2 回答 2

0

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

于 2013-05-12T02:37:12.343 回答
0

上面的答案是正确的 - 但您可能希望尽量减少与主要功能进行的字符串比较量(它很快变得难以维护,并且您有绝佳的机会将用户输入封装为布尔值)

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

    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...");
            }
        }
    }
于 2013-05-12T02:58:13.313 回答