BufferedReader的无限循环

时间:2015-02-03 17:17:17

标签: java string bufferedreader tokenize

我正在尝试使用BufferedReader和StringTokenizer读取用户的某些输入,但输入不会终止。

  BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
  StringTokenizer st;
  st = new StringTokenizer(reader.readLine());
  N = Integer.parseInt(st.nextElement().toString());
  M = Integer.parseInt(st.nextElement().toString());
  System.out.println(N+"\n"+M);
  for(int i = 0; i < M; i++) {
      st = new StringTokenizer(reader.readLine());
      System.out.println(st);
      int t1 = Integer.parseInt(st.nextElement().toString());
      int t2 = Integer.parseInt(st.nextElement().toString());
      ad.add(t2);
      path.put(t1, ad);
      System.out.println(t1+"and"+t2);

      //path.put(t2, t1);
      System.out.println(path);
  }
  st = new StringTokenizer(reader.readLine());

  int s = Integer.parseInt(st.nextElement().toString());
  int t = Integer.parseInt(st.nextElement().toString());

它确实来自循环(通过使用print语句得出结论)。

输入格式也是:

3 3
1 3
1 2
2 3
1 3

1 个答案:

答案 0 :(得分:1)

我刚刚运行它,它确实突破了循环。我改变的是删除未编译的行(ad.add(t2)和下一行)并放入&#34; int&#34;在变量名之前......

public static void main(String[] args) throws Exception {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    StringTokenizer st;
    st = new StringTokenizer(reader.readLine());
    int N = Integer.parseInt(st.nextElement().toString());
    int M = Integer.parseInt(st.nextElement().toString());
    System.out.println(N + "\n" + M);
    for (int i = 0; i < M; i++) {
        st = new StringTokenizer(reader.readLine());
        System.out.println(st);
        int t1 = Integer.parseInt(st.nextElement().toString());
        int t2 = Integer.parseInt(st.nextElement().toString());
        System.out.println(t1 + "and" + t2);

    }
    st = new StringTokenizer(reader.readLine());

    int s = Integer.parseInt(st.nextElement().toString());
    int t = Integer.parseInt(st.nextElement().toString());
}

...输出

3 3 (I typed this)
3
3
1 3 (I typed this)
java.util.StringTokenizer@46f5331a
1and3
1 2 (I typed this)
java.util.StringTokenizer@bee145b
1and2
2 3 (I typed this)
java.util.StringTokenizer@3b7a687b
2and3
1 3 (I typed this)

程序然后终止