1

My title's a bit poor, but here's the issue. I'm using the Scanner class to take 2 inputs, both integers. If one is not an integer, it tells the user to put in another input. This works fine for the first integer, but on the second integer (and any consecutive ones), it prints out the text twice.

Code:

public class Project1 {
    public static void main(String[] args) {
        // creates a new scanner
        Scanner scanner = new Scanner(System.in);

        // rejects input if the first token is not an integer
        System.out.println("Enter the first integer:");
        while(!scanner.hasNextInt()) {
            scanner.nextLine();
            System.out.println("That's not an integer, please enter again:");
        }
        // stores integer in variable when first token is an integer
        int num1 = scanner.nextInt();

        /* ======== repeats for second integer ======== */
        System.out.println("Enter the second integer:");
        while(!scanner.hasNextInt()) {
            scanner.nextLine();
            System.out.println("That's not an integer, please enter again:");
        }
        // stores integer in variable when first token is an integer
        int num2 = scanner.nextInt();

        System.out.println(num1 + num2);
    }
}

Here's the result:

"Enter the first integer:"
>1.2
"That's not an integer, please enter again:"
>1
"Enter the second integer:"
>2.3
"That's not an integer, please enter again:"
"That's not an integer, please enter again:"
>2
"3"

Why does it repeat twice for the second integer?

Cameron
  • 229
  • 2
  • 10

1 Answers1

2

Rather than using nextLine() to skip the line,use next() method of Scanner class.

So,now the following code works fine.

import java.util.*;
public class Project1 {
    public static void main(String[] args) {
        // creates a new scanner
        Scanner scanner = new Scanner(System.in);

        // rejects input if the first token is not an integer
        System.out.println("Enter the first integer:");
        while(!scanner.hasNextInt()) {
           // scanner.nextLine();
            scanner.next();
            System.out.println("That's not an integer, please enter again:");
        }
        // stores integer in variable when first token is an integer
        int num1 = scanner.nextInt();

        /* ======== repeats for second integer ======== */
        System.out.println("Enter the second integer:");
        while(!scanner.hasNextInt()) {
            //scanner.nextLine();
            scanner.next();
            System.out.println("That's not an integer, please enter again:");
        }
        // stores integer in variable when first token is an integer
        int num2 = scanner.nextInt();

        System.out.println(num1 + num2);
    }
}

OUTPUT

Enter the first integer:
1.2
That's not an integer, please enter again:
2
Enter the second integer:
1.3
That's not an integer, please enter again:
3
5
asad_hussain
  • 1,684
  • 1
  • 11
  • 24