System.in.read(byte[])
读到byte数组中再转

解决方案 »

  1.   

    给你个调试好的完整的程序,供你参考!public class ReadLine
    {
    public static void main(String [] args)
    {
    byte buf[]=new byte[1024];
    String strinfo=null;
    int pos=0;
    int ch=0;
    System.out.println("Please enter info");
    while(true)
    {
    try
    {
    ch=System.in.read();
    }
    catch(Exception e)
    {
    e.printStackTrace();
    }
    if(ch=='\r' || ch=='\n')
    break;
    else
    {
        buf[pos++]=(byte)ch;
    }
    }
    strinfo=new String(buf,0,pos);
    System.out.println(strinfo);
    }
    }
      

  2.   

    也可以参考楼上的。大概如下:
        byte[] b = new byte[4];   //假设最大4位数
        int n = 0;
        if (System.in.read(b) != -1) {  
          for (int i = b.length - 1; i > 0; --i) {
            if (b[i] == '\n') {
              n = i;
              break;
            }
          }
          if (n > 0) System.out.println("your input is " + Integer.parseInt(new String(b, 0, n)));
        }
      

  3.   


    BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
    String inLine = bf.readLine();
    int n = Integer.parseInt(inLine);就这样,不过要用try catch保护起来。当用户输入整数时,一切正常。当用户输入的格式不对时,最后一行代码会抛出异常。 你在catch块里可以进行相应处理,比如提醒用户重新输入。
      

  4.   

    谢谢! 不过我试了, 不对啊!
    打印出来的是输入了几位数字, 我想要的是得到一个int i=键盘输入
    如果输入99, 则i=99.
      

  5.   

    同意: honkiko(honky) 的一说。
    好好看看java书吧。好像每本书都会讲的,一般在I/O那章
      

  6.   


    class ReadInt {
      public ReadInt() {}  public static int getInt() {
        byte[] bs = new byte[20];
        int length = 0;
        try {
          length = System.in.read(bs);
        }
        catch (IOException ex) {
        }
        if (length < 2) {
          return 0;
        }
        try {
          return Integer.parseInt(new String(bs, 0, length - 2));
        }
        catch (NumberFormatException ex1) {
          return 0;
        }
      }
    }