1

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

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"));



}

   }

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

4

3 回答 3

2

移动keyboard.nextLine();aftern2 = keyboard.nextInt();接受并忽略调用.nextInt()

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

于 2015-04-24T06:26:31.880 回答
0

改变 的位置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());
于 2015-04-24T06:29:54.903 回答
0
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();
}
于 2015-04-24T06:31:38.587 回答