Sergey Shustikov
Sergey Shustikov

Reputation: 15821

Read string line from console

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.

Upvotes: 0

Views: 91

Answers (2)

romaneso
romaneso

Reputation: 1122

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();
}

Upvotes: 0

Maroun
Maroun

Reputation: 95968

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'.

Upvotes: 2

Related Questions