在java中无限循环

Kar*_*k.m 3 java

我是Java新手.我试图从文本文件中提取员工数据并将其存储在集合中.我使用Stringtokenizer从文件中获取字符串,但在第二次迭代中,while循环变为无限; 它不会出现在while循环中.我的代码是:

public class Reader1 {
    String a;
    int i = 0;
    int count = 0;
    int x = 0;
    int y = 0;
    File f = new File(
            "C:\\Documents and Settings\\kmoorthi\\Desktop\\ak\\sample.txt");

    ArrayList<Employee> al = new ArrayList<Employee>();

    public void notePad() throws IOException {

        try {
            FileReader fis = new FileReader(f);
            BufferedReader br = new BufferedReader(fis);

            do {
                a = br.readLine();
                i++;
                if (i > 1) {
                    if (a != null) {
                        StringTokenizer st = new StringTokenizer(a, "    ");
                        Employee e = new Employee();
                        System.out.println("hai1");
                        while (st.hasMoreTokens()) // here became infinite
                        {
                            count++;
                            if (count == 1) {
                                e.ename = st.nextToken();
                                al.add(e);
                            }

                            if (count == 2) {
                                e.eno = st.nextToken();
                                al.add(e);
                            }
                        }
                    }
                }
            } while (a != null);
            br.close();

        } catch (FileNotFoundException q) {
            q.printStackTrace();
        }
    }

    public void retrieve() {
        Iterator<Employee> it = al.iterator();
        while (it.hasNext()) {
            Employee fi = (Employee) it.next();
            String en = fi.ename;
            System.out.println(en);
        }
    }

    public static void main(String s[]) throws IOException {
        Reader1 r = new Reader1();
        r.notePad();
        r.retrieve();
    }
}
Run Code Online (Sandbox Code Playgroud)

请提出解决方案.

Car*_*icz 9

嗯,那么count到3 时会发生什么?你不再打电话,nextToken所以你永远不会用完代币.

你真的不需要那个内循环.你总是想从那个字符串中拉出2个标记,所以就这样做吧!但是,如果一行没有2个令牌,您可能需要一些错误处理.