且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

解析输入而不使用除System.in.read()之外的任何内容

更新时间:2023-02-19 19:52:04

问题不在于System.in.read(),而在于控制台。
控制台通常是缓冲的,这意味着只有在按下回车键后才能将数据发送到您的程序(因此可由System.in.read()读取)。
所以你必须将控制台切换到无缓冲模式,但没有可移植的方法来执行此操作,因为有太多不同类型的控制台(unix shell,cmd窗口,Eclipse控制台等)。 br>
如果不允许使用除System.in.read()和System.out.println()方法之外的任何内容,则必须让用户在一行中输入完整的术语,按回车键并输入然后你可以处理输入的字符,例如:

The problem is not with System.in.read(), but with the console. The console is usually buffered, that means data is sent to your program (and thus readable by System.in.read()) only after the enter key is pressed. So you would have to switch the console to an unbuffered mode, but there is no portable way to do this, because there are so much different types of consoles (unix shell, cmd window, Eclipse console etc.).
If you are not allowed to use anything other than System.in.read() and System.out.println() methods, you have to let the user enter the complete term in a line, press enter and then you can process the characters entered, e.g:

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");
    }
}