Aishu Aishu - 14 days ago 7
Java Question

Printing character in java

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?

Answer

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.

Comments