【问题标题】:Java program asking user to continueJava 程序要求用户继续
【发布时间】:2014-10-02 14:19:02
【问题描述】:
public static void main(String [] args) {
    Scanner input = new Scanner(System.in);
    double dblNumber, dblSquare, dblSqrt;
    String answer;
    String answery = "yes";
    String answern = "no";

    while (true) {
        System.out.println( "Welcome to Squarez! Where we do the math for you.\nPlease input a number you would like us to do some math with.");
        dblNumber = input.nextDouble();
        dblSqrt = Math.sqrt(dblNumber);
        dblSquare = Math.pow(dblNumber, 3);
        System.out.println("" + dblSquare + " " + dblSqrt);

        System.out.println("Would you like to continue?");
        answer = input.nextLine();

        if (answer.equals(answery)) {
            System.out.println("You answered yes");

        }
        if (answer.equals(answern)) {
            System.out.println("You answered no.");
            System.exit(0);

        }
    }
}

程序运行并完全忽略询问用户是否要继续的提示。它直接回到第一个数字的提示。为什么要跳过它?

【问题讨论】:

    标签: java loops


    【解决方案1】:

    你必须在你的双倍之后消耗换行符:

      System.out.println("Would you like to continue?");
      input.nextLine();              // <-- consumes the last line break
      answer = input.nextLine();     // <-- consumes your answer (yes/no)
    

    【讨论】:

      【解决方案2】:

      您阅读了声明中的数字

      dblNumber = input.nextDouble();
      

      虽然此行会阻塞,直到用户输入整行(包括换行符),但只有没有换行符的字符会被解析并以双精度形式返回。

      这意味着,换行符仍在等待从扫描仪中检索!线

      answer = input.nextLine();
      

      直接就是这样做的。它使用换行符,为变量answer 提供一个空字符串。

      那么,解决方案是什么?始终使用input.nextLine() 读取用户输入,然后根据需要解析生成的字符串:

      String line = input.nextLine();
      dblNumber = Double.parseDouble(line);
      

      【讨论】:

        【解决方案3】:

        应该是这样的:

        String answer;
        String answery = "yes";
        String answern = "no";
        
        System.out.println("Would you like to continue?");
        input.nextLine();          
        answer = input.nextLine(); 
        

        而您只有两个决定来做出“是”或“否”,我真的不明白您为什么使用 2 个 if 语句;虽然您刚刚为答案的“是”部分执行了此操作,而相反的部分将是“否”。

            if(answer.equals(answery))  
            {             
            System.out.println("You answered yes");    
            }
        
            else
            System.out.println("You answered no.");
            System.exit(0);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-05-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-04-01
          • 1970-01-01
          • 2011-07-01
          相关资源
          最近更新 更多