如何在循环外使用BufferedReader从键盘输入?

时间:2012-06-03 07:10:13

标签: java bufferedreader java-io

InputStreamReader inp= new InputStreamReader(System.in);
do  
{  
  BufferedReader br = new BufferedReader(inp);  
  System.out.println("Enter Roll number : ");  
  int rno= Integer.parseInt(br.readLine());   

  System.out.println("Enter name: ");  
  String name= br.readLine();

  System.out.println("Continue y/n: ");  
  char ans=(char)br.read();  
} while(ans=='y');    

如何在循环外编写BufferedReader?如果我在外面使用它,它会显示以下异常:

java.lang.numberformatexception for input string at            
    java.lang.Integer.parseInt(Integer.java:468)

是否有任何机制可以刷新BufferedReader?可以做些什么?

1 个答案:

答案 0 :(得分:0)

这不是'好'但对我有用 - 我添加了br.readLine():

public static void main(String args[]) throws IOException {
    BufferedReader br = null;
    try {
        InputStreamReader inp = new InputStreamReader(System.in);
        br = new BufferedReader(inp);
        char ans;
        do {
            System.out.println("Enter Roll number : ");
            int rno = Integer.parseInt(br.readLine());

            System.out.println("Enter name: ");
            String name = br.readLine();

            System.out.println("Continue y/n: ");
            ans = (char) br.read();
            br.readLine();
        } while (ans == 'y');
    } finally {
        if (br != null) {
            br.close();
        }
    }
}