我很难找到有关 System.in.read();
究竟如何工作的详细信息,也许有人可以帮助我。似乎 Scanner 更可取,但我不允许使用它。
我被分配了一个任务,我应该读取 boolean -运算符- boolean 形式的控制台用户输入,例如T^F 或 T&T 通过 System.in.read()
并简单地打印语句返回的内容。
普通人可能会使用不同的方法,但作业明确指出只允许使用 System.in.read()
和 System.out.println()
.
这是我尝试解决的问题:
import java.io.*;
public static void main(String[] args) {
String error = "Reading error, please use T or F";
boolean a = true; //char: 84 or 116 for T and t
boolean b = false; //char: 70 or 102 for F and f
int userChar1;
int userOperator;
int userChar2;
int chosenOperator = 0;
try {
//Get first char
System.out.println("Enter the first value (T or F):");
userChar1 = System.in.read();
if((userChar1==84)||(userChar1==116)) { // T or t
a = true;
} else if ((userChar1==70)||(userChar1==102)) { // F or f
a = false;
} else {
System.out.println(error);
}
//Get second char
System.out.println("Select an operator: & | ^");
userOperator = System.in.read();
if(userOperator==38) { // &
chosenOperator = 0;
} else if (userOperator==124) { // |
chosenOperator = 1;
} else if (userOperator==94) { // ^
chosenOperator = 2;
} else {
System.out.println(error);
}
//Get third char
System.out.println("Enter the second value:");
userChar2 = System.in.read();
System.in.close();
if((userChar2==84)||(userChar2==116)) {
b = true;
} else if ((userChar2==70)||(userChar2==102)) {
b = false;
} else {
System.out.println(error);
}
//Figure out result
boolean result;
switch (chosenOperator) {
case 0:
result = a&b;
case 1:
result = a|b;
case 2:
result = a^b;
System.out.println(result);
}
} catch(IOException e) {
}
}
执行此代码会使控制台在第一个 System.in.read()
之后等待用户输入,并让它正确检查字符输入。然而,在那之后,所有后续的 System.in.read()
都将被忽略并且程序终止。
我发现了一段使用了 System.in.close()
的代码,所以仍然不知道我在每次 System.in.read( )
。当调用 System.in.close()
之后的第一个 System.in.read()
时,这会导致程序终止。
那么,到底是怎么回事呢?您将如何正确使用 System.in.read()
?
最佳答案
问题不在于 System.in.read(),而在于控制台。
控制台通常是缓冲的,这意味着只有在按下回车键后,数据才会发送到您的程序(因此可由 System.in.read() 读取)。
因此,您必须将控制台切换到无缓冲模式,但没有可移植的方法来执行此操作,因为有太多不同类型的控制台(unix shell、cmd 窗口、Eclipse 控制台等)。
如果不允许使用 System.in.read() 和 System.out.println() 方法以外的任何方法,则必须让用户在一行中输入完整的术语,然后按回车键,然后才能处理字符输入,例如:
public static void main(String[] args) throws IOException {
boolean a = true; // char: 84 or 116 for T and t
boolean b = false; // char: 70 or 102 for F and f
int userChar1;
int userOperator;
int userChar2;
System.out.println("Please enter the term, e.g. T&F:");
userChar1 = System.in.read();
userOperator = System.in.read();
userChar2 = System.in.read();
a = userChar1 == 'T' || userChar1 == 't';
b = userChar2 == 'T' || userChar1 == 't';
switch (userOperator) {
case '&':
System.out.println(a & b);break;
case '|':
System.out.println(a | b);break;
case '^':
System.out.println(a ^ b);break;
default:
System.out.println("unknow operator");
}
}
关于java - 只使用 System.in.read() 解析输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13109996/