简体   繁体   中英

How to use System.in.read() in java?

I need to input and load some chars in a boolean 2-D array. If the char is X , mark the array element as true ; else if the char is . , mark the array element as false.

Here is my design:

boolean[][] Array = new boolean[2][2];

for (int i = 0; i < 2; i++) {  
   for (int j = 0; j < 2; j++) {
        if (System.in.read() == '.') {
            Array[i][j] = false;
        } else if (System.in.read() == 'X') {
            Array[i][j] = true;
        }
    }
}

And, for example, if I type in .... or XXXX , it does not produce the correct result. Also for other input the result is not correct.

So how to deal with this?

You are reading a character a second time in the loop if the first character is not a '.' .

You should only read one character per loop. Save the character in a variable before your if statement, and then compare the variable to '.' and 'X' in turn.

You shouldn't call the read() function in each if statement. Call it one time and store it in a variable so you don't keep reading through the input. That could be one thing messing up your function. Another is how you are comparing char s with the == operator. Should use char.equals method for character comparison. Put a couple breakpoints in and see what values are being sent through to debug. Maybe try something like the following:

boolean[][] Array= new boolean[2][2];

for (int i = 0; i < 2; i++) {  
  for (int j = 0; j < 2; j++) {
        Character input = (char)System.in.read();
        if (input.equals('.')) {
            Array[i][j] = false;
        } else if (input.equals('X')) {
            Array[i][j] = true;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM