Search code examples
javaloopsdo-loops

Prompting user to continue not working, java


I need help. I want to ask the user if he wants to try again, but something seems to be wrong with my code, because it's not working.

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



}

   }

When I run it, it stores the user's answer, yet the program doesn't repeat. How can I fix this?


Solution

  • Move the keyboard.nextLine(); after n2 = keyboard.nextInt(); to accept and ignore the dangling newline character in the inputstream left behind by call to nextInt().

    When I run it, it stores the user's answer - Try printing what it has stored in the answer field then you will see the problem.