如何检查用户是否输入“是”或“否”而没有其他内容?

时间:2015-09-29 18:59:53

标签: java

我想知道是否有办法让程序不能继续,除非用户只输入“是”“否”。通常当我使用answer.equalsIgnoresCase(" ")时,如果我输入“dog”这个词,它就会充当“是”。有人可以帮忙吗?

目前我有这样的话:

System.out.println("\nDo you want to add another item? (Yes/No)");
answer = br.readLine();

switch (answer) {
    case "YES":
    case "Yes":
    case "yes":
    case "y":
        continue;

    case "NO":
    case "No":
    case "no":
    case "n":
        break;

    default:
        System.out.println("\nWarning: You need to enter Yes or No!!. Do you want to enter another item? (Yes/No)");
        answer = br.readLine();

        if (answer.equalsIgnoreCase("Yes")) {
            continue;
        } else
            break;
}

输出:

  

~~~~~ WELCOME ~~~~~
  输入商品代码
  #KV1
  输入项目描述
  豌豆
  输入项目重量
  2.2
  输入商品价格
  $ 3个
  要添加其他商品吗? (是/否)
  狗
  警告:您需要输入是或否!!你想输入另一个项目吗?(是/否)
  狗
  物品清单:

     

1)
  商品代码:#Kv1
  项目描述:豌豆
  项目重量克数:2.20
  单价:$ 3.00

1 个答案:

答案 0 :(得分:0)

当你进入" dog,"你输入这个开关块

default:
        System.out.println("\nWarning: You need to enter Yes or No!!. Do you want to enter another item? (Yes/No)");
        answer = br.readLine();

        if (answer.equalsIgnoreCase("Yes")) {
            continue;
        } else
            break;

当你进入" dog"再次,answer.equalsIgnoreCase("Yes")评估为false并且它从循环中断开。这就是为什么" dog"表现得很奇怪;你的默认情况确保任何两个背靠背"错误"输入将失败。由于我们无法看到外部循环,因此很难解决您的确切问题......但重新考虑您的开关逻辑块。由于您尝试使其行为像while循环,可能会重新设计它:

    System.out.println("\nDo you want to add another item? (Yes/No)");
    String answer;

    // Assuming br is some instance of a Scanner
    while( !(answer = br.nextLine()).equalsIgnoreCase("no") ) {
        if(answer.equalsIgnoreCase("yes")) {
            //Do your logic for yes
            System.out.println("Hooray, you entered yes...");
            System.out.println("Do you want to add another item? (Yes/No)");
        } else {
            System.out.println("\nWarning: You need to enter Yes or No!!. Do you want to enter another item? (Yes/No)");
        }
    }

    // Print the results…
    System.out.println("Hooray, you entered no...");