0
    Scanner scan = new Scanner(System.in);
    String in;
    int count = scan.nextInt();
    for (int i = 0; i < count; i++){
        System.out.print("Input "+i+" of "+count+": ");
        in = scan.nextLine();
    }

As the title says, this for loop prints the line twice (with the "i" variable incremented once) before it stops to wait for user input. I don't understand why it does that. I tried to use while loop, with similar results. Help?

EeveeLover
  • 89
  • 5
  • 1
    add a simple scan.next(); or scan.nextLine(); after your scan.nextInt(); and before your loop. or read a String in the first statement, and parse it to an int. – Stultuske Sep 02 '19 at 12:53

2 Answers2

1

You should add scan.nextLine(); after scan.Int();.

Scanner scan = new Scanner(System.in);
String in;
int count = scan.nextInt();
scan.nextLine();
Abnaby
  • 45
  • 8
0

Try this :

Scanner scan = new Scanner(System.in);
String in;
int count = Integer.parseInt(scan.next());
for (int i = 0; i < count; i++){
    System.out.print("Input "+i+" of "+count+": ");
    in = scan.nextLine();
}

Keep in mind, you need to handle NaN exception


Alternative, as suggested by @Stultuske in a comment, add scan.nextLine(); or scan.next(); after scan.nextInt();

Shrey Garg
  • 1,217
  • 1
  • 5
  • 15