Why unwanted assignment is occuring?
The keyboard input character(s) is stored in input buffer after ENTER is pressed. ENTER includes line feed '\n' in the input character. Decimal/integer value of line feed '\n' is 10.
System.in.read() reads only first one character from the input character(s), the character is casted into integer and return it.
And that character will be excluded from the input buffer.
The rest of the characters are still pending in the input buffer until it is read by System.in.read() in the same manner stated above.
int inputchar1, inputchar2, inputchar3;
System.out.print("input: ");// input: 43
// The line feed '\n' is generated when ENTER is pressed.
// '4', '3' and '\n' are in the input buffer.
inputchar1 = System.in.read(); // '4' is read and returns 52 (corresponding integer value)
// '3' and '\n' is in the input buffer.
inputchar2 = System.in.read(); // '3' is read and returns 51
// '\n' is pending in the input buffer.
inputchar3 = System.in.read(); // '\n' is read and returns 10
// no more input character in the input buffer.
System.out.println("inp1 =" + inputchar1);
System.out.println("inp1 =" + inputchar2);
System.out.println("inp1 =" + inputchar3);
/*
* Refer to ASCII table for char to decimal conversion.
* Although java Char is 16-bit unicode ASCII is still applicable.
*/
How to avoid unwanted assignment?
Keep reading the content of input buffer until it gets depleted.
int x, y, avoid;
System.out.println("Enter x: ");
x = System.in.read();
// Reading all the characters after the first character so that
// no character stays pending in the input buffer.
do {
avoid = System.in.read();
} while(avoid != '\n');
System.out.println("Enter y: ");
// New input buffer is created.
y = System.in.read();
do {
avoid = System.in.read();
} while(avoid != '\n');
Reference: "Java: A beginner's guide 6e" - Herbert Schildt