Topic: java系统输入截获后为什么不和输出的结果相同?

  Print this page

1.java系统输入截获后为什么不和输出的结果相同? Copy to clipboard
Posted by: phoenix451
Posted on: 2005-11-03 18:39

今天我在试着编写从键盘接受数据的时候,忽然想多循环几次,
可是,就在我循环的时候出现了问题:
以下是我的程序:
import java.io.*;
public class Sysin {
  public static void main(String[] args)throws IOException
  {
  InputStreamReader in = new InputStreamReader(System.in);
    BufferedReader bufin = new BufferedReader(in);
    for (int i = 0; i < 5; i++) {
      int tem;
      tem = bufin.read();
      System.out.println(tem);
    }  
  }
}
当编辑运行的时候,我的打算是输入1,2,3,4,5,然后输出1,2,3,4,5,可是当我输入1时,系统输出:49,13,10当我输入2时,系统输出:50,13,循环就结束了
我不理解为什么循环只循环了两次就结束了?
那位大大可以告诉我这是怎么回事?
要不我会睡不着的

2.Re:java系统输入截获后为什么不和输出的结果相同? [Re: phoenix451] Copy to clipboard
Posted by: hualee
Posted on: 2005-11-04 12:24

应该问题出在 BufferedReader这里,缓冲区没清空,我是这样理解的,不知道表达是不是很准确,我也是个菜鸟呢:)看下面的代码,我帮你修改的,注释的是错误处
import java.io.*;
public class Sysin {
public static void main(String[] args)throws IOException
{
InputStreamReader in = new InputStreamReader(System.in);
//BufferedReader bufin = new BufferedReader(in);
for (int i = 0; i < 5; i++) {
int tem;
BufferedReader bufin = new BufferedReader(in);
tem = bufin.read();
System.out.println(tem);
}
}
}

3.Re:java系统输入截获后为什么不和输出的结果相同? [Re: phoenix451] Copy to clipboard
Posted by: 逍遥神仙
Posted on: 2005-11-04 18:11

import java.io.*;
public class Sysin {
public static void main(String[] args)throws IOException
{
InputStreamReader in = new InputStreamReader(System.in);
BufferedReader bufin = new BufferedReader(in);
for(int i=0;i<5;i++){

String tem;
tem = bufin.readLine();
System.out.println(tem);
}
}
}

把 int tem 改成 String tem


   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923