class stringTest 
{
public static void mb_operate()
{
System.out.println("Hello World!");
}

public static void main(String[] args) 
{
char c=0;
while(true){
mb_operate();
try{
c = (char)System.in.read();
}catch(IOException e){
System.err.println("Error!");
}
switch(c){
case '+':System.out.println("case : +");break;
case '-':System.out.println("case : -");break;
case '*':System.out.println("case : *");break;
case '/':System.out.println("case : /");break;
default:System.out.println("default:Error");break;
}
}
}
}用read()读取怎么不对呢?总是输出莫名其妙的样式。比如我输入一个加号,确出现三次循环,并不是每次循环到read()就等待我输入然后根据我的选择再运行,我是想解决用read实现。
Hello World!
+
case : +
Hello World!
default:Error
Hello World!
default:Error
Hello World!

解决方案 »

  1.   

    试一下下面的程序,你就明白了。import java.io.IOException;
    public class Test {    public static void main(String[] args) throws IOException {
            while (true) {
                int i = System.in.read();
                System.out.println(i);
            }
        }
    }这个程序运行时:D:>java Test
    +     ----- 输入后找回车键了吧
    以下为输出:
    43    ----- '+'的编码
    13    ----- 换行的编码
    10    ----- 回车的编码也就是说你输入一个“+”并找回车时,对System.in.read()来说,你输入了3个字符。因此循环3次。