我需要从控制台逐字节读取输入,然后打印出来,然后检查它是否等于“exit”。
这是我的代码:
int inChar = 1;
String input = "";
char correctChar;
// code
try {
while (inChar != '\n') {
inChar = System.in.read();
correctChar = (char) inChar;
if (inChar != '\n') {
input += correctChar;
} // end if
} // end while
} // end try
catch (IOException e) {
System.out.println("Error reading from user");
} // end catch
System.out.println("Hello " + input + "AQ");
出于某种原因,当我运行代码并输入 exit 时,它会打印到屏幕上:
AQllo 退出
如果我检查是否input.equals("exit")
它说不。我的猜测是字符串不是以 null 结尾的,因为这是我在汇编中遇到类似问题时出现的问题,但我似乎无法修复此 Java 代码。我是否能正确地从屏幕上读取字节?
最佳答案
我假设您在 Windows 计算机上工作,对吧?
问题是,如果你在控制台输入一些内容,你将输入:exit\r\n
,因为\r\n
是Windows的行分隔符.
现在,由于您的检查 while (inChar != '\n')
和 if (inChar != '\n')
,但您将 \r
附加到您的 input
字符串中。 \r
是 carriage return它将光标移动到行的开头。
现在让我们检查您的输出:
System.out.println("Hello " + input + "AQ");
您正在打印此内容:
Hello exit\rAQ
某些控制台(不是 Eclipse 或 IDEA 等 IDE 中的控制台)会解释 \r
并移动光标。这意味着,您将光标移动到行首,然后打印 "AQ",这会覆盖前两个字母 "He",因此输出:
AQllo exit
要解决此问题,只需添加对 \r
的额外检查:
int inChar = 1;
String input = "";
char correctChar;
// code
try {
while (inChar != '\n' && inChar != '\r') {
inChar = System.in.read();
correctChar = (char) inChar;
if (inChar != '\n' && inChar != '\r') {
input += correctChar;
} // end if
} // end while
} // end try
catch (IOException e) {
System.out.println("Error reading from user");
} // end catch
System.out.println("Hello " + input + "AQ");
关于Java附加随机字符并覆盖字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31095021/