You can use the Scanner
class, which consumes input more predictably:
public static void main(String arg[]) throws IOException {
int k, i;
char a;
k = 0;
Scanner in = new Scanner(System.in);
for (i = 0; i <= 3; i++) {
k++;
a = in.next().charAt(0);
System.out.println(k);
}
}
The next()
method returns a string, consisting of all the characters typed by the user, until they press the key. So, by typing one character at a time (or by typing the desired character first), the string returned by next()
will start with that character, so calling charAt(0)
will retrieve it.
Note that there is no reason to run the loop for the first 4 times (0, 1, 2 and 3). You could replace the for
statement with a while (true)
statement.