[英]How to use System.in.read() in java?
I need to input and load some chars in a boolean 2-D array. 我需要在布尔2-D数组中输入和加载一些字符。 If the char is
X
, mark the array element as true
; 如果char为
X
,则将数组元素标记为true
; else if the char is .
否则,如果char是
.
, mark the array element as false. ,将数组元素标记为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. 并且,例如,如果我输入
....
或XXXX
,它不会产生正确的结果。 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 '.'
在
if
语句之前将字符保存在变量中,然后将变量与'.'
进行比较'.'
and 'X'
in turn. 和
'X'
反过来。
You shouldn't call the read()
function in each if
statement. 您不应该在每个
if
语句中调用read()
函数。 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. 另一个是你如何比较
char
和==
运算符。 Should use char.equals
method for character comparison. 应该使用
char.equals
方法进行字符比较。 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;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.