Reputation: 1320
I'm trying print a given String char by char:
public static void main(String[] args) {
char c;
Scanner scaner = new Scanner(System.in);
int length = scaner.next().length();
System.out.println(length);
int i = 0;
while (i < length) {
c = scaner.next().charAt(i);
System.out.println(c);
i++;
}
}
Once this code has reached int length = scaner.next().length();
it doesn't continue. What's causing this?
Upvotes: 1
Views: 108
Reputation: 466
You need to enter something after calling next().
As addition too Alexander's answer.
The line: int length = scaner.next().length();
gets the next line and then checks the length.
So you already got the next line and calling next() again asks for different input.
That's the reason why you should always store the return value of next() in a variable!
Upvotes: 1
Reputation: 45576
You should store the scanned value in the temporary variable.
char c;
Scanner scaner = new Scanner(System.in);
// Storing scanned value
String nextStr = scaner.next();
int length = nextStr.length();
System.out.println(length);
int i = 0;
while(i < length){
c = nextStr.charAt(i);
System.out.println(c);
i++;
}
In your original code you call next
repeatedly in a loop, but this does not return the original scanned value, but the next line of input.
Upvotes: 4