【问题标题】:Prompting user to continue not working, java提示用户继续不工作,java
【发布时间】:2015-04-24 06:25:34
【问题描述】:

我需要帮助。我想问用户是否想再试一次,但我的代码似乎有问题,因为它不起作用。

public class TotoAzul
{
   public static void main(String[] args)
   {

      Scanner keyboard = new Scanner(System.in);

      int n1, n2, sum;
      String answer;
      do {

      System.out.println("Enter number 1: ");
      n1 = keyboard.nextInt();

      System.out.println("Enter number 2: ");
      n2 = keyboard.nextInt();

      sum = n1 + n2;

      System.out.println("Number 1\t" + "Number 2\t" + "Sum");
      System.out.println("__________________________________");
      System.out.println(n1 + "\t\t" + n2 + "\t\t" + sum);

      System.out.println("Enter yes to continue or any other key to end");
      answer = keyboard.nextLine();

      keyboard.nextLine();

      }
      while(answer.equalsIgnoreCase("YES"));



}

   }

当我运行它时,它会存储用户的答案,但程序不会重复。我该如何解决这个问题?

【问题讨论】:

  • 已修复,谢谢各位。

标签: java loops do-loops


【解决方案1】:

keyboard.nextLine(); 移动到n2 = keyboard.nextInt(); 之后,以接受并忽略调用nextInt() 留下的输入流中的悬空换行符

当我运行它时,它会存储用户的答案 - 尝试打印它存储在 answer 字段中的内容,然后你会看到问题。

【讨论】:

    【解决方案2】:
    Scanner keyboard = new Scanner(System.in);
    
          int n1, n2, sum;
          String answer = "Yes";
    
    while (answer.equals("Yes"))
    {
     System.out.println("Enter number 1: ");
          n1 = keyboard.nextInt();
    
          System.out.println("Enter number 2: ");
          n2 = keyboard.nextInt();
    
          sum = n1 + n2;
    
          System.out.println("Number 1\t" + "Number 2\t" + "Sum");
          System.out.println("__________________________________");
          System.out.println(n1 + "\t\t" + n2 + "\t\t" + sum);
    
          System.out.println("Enter yes to continue or any other key to end");
          answer = keyboard.nextLine();
    
          keyboard.nextLine();
    }
    

    【讨论】:

      【解决方案3】:

      更改keyboard.nextLine();的位置。

      keyboard.nextLine();
      answer = keyboard.nextLine();
      

      在您的代码中,答案是下一行(即enter),当您取 n2 的值并按 Enter 键时,它就会出现。


      您可以通过执行以下代码来测试您的代码

      System.out.println("Enter yes to continue or any other key to end");
      answer = keyboard.nextLine();
      System.out.println("Answer : " + answer);
      System.out.println(keyboard.nextLine());
      

      【讨论】:

        猜你喜欢
        • 2022-01-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多