0

I need to create an array from console.

I do:

int forbiddenSequenceCount = scanner.nextInt();//1
String[] forbidden = new String[forbiddenSequenceCount];//2
for (int k = 0; k < forbiddenSequenceCount; k++) {//3
    forbidden[k] = scanner.nextLine(); //4
}

But when I input forbiddenSequenceCount = 1 line 4 was not waiting while I input String.
It's just executed.

What i'm doing wrong?

Input :

2
3 0 1 0

I need put 3 0 1 0 to array.

Maroun
  • 94,125
  • 30
  • 188
  • 241
Sergey Shustikov
  • 15,377
  • 12
  • 67
  • 119

2 Answers2

2

scanner.nextInt() reads only the int value, the '\n' (the enter you press right after you type the int) is consumed in scanner.nextLine().

To fix this add scanner.nextLine() right after scanner.nextInt() so it'll consume that '\n'.

Maroun
  • 94,125
  • 30
  • 188
  • 241
  • I will accept this answer during9 minutes. Stack disallow me this now. – Sergey Shustikov Jul 23 '14 at 08:37
  • @deathember You're welcome, make sure you understand what happened in your code to avoid this problem next time. You can also have a different instance of `Scanner`.. But the solution I provided is fine. – Maroun Jul 23 '14 at 08:38
0

You just have to think of this:

Scanner sc = new Scanner(System.in);
 int i = sc.nextInt();

So, in your case, it goes like that:

int forbiddenSequenceCount = scanner.nextInt();
String[] forbidden = new String[forbiddenSequenceCount];
for (int k = 0; k < forbiddenSequenceCount-1; k++) {
    forbidden[k] = scanner.next();
}
romaneso
  • 1,097
  • 1
  • 10
  • 26