我是Java新手。我试图从文本文件中提取员工数据并将其存储在集合中。我使用Stringtokenizer从文件中获取字符串,但在第二次迭代中,while循环变为无限;它不会从while循环中出来。我的代码是:无限循环在java中
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();
}
}
请建议解决方案。
我已经只有两根弦的每一行像 汤姆5647 詹姆斯4628 所以ST只有两个令牌后,而循环应该出来正确 – 2009-11-20 06:45:45
如果它工作正常,你不会寻求帮助。只要做'e.ename = st.nextToken(); e.eno = st.nextToken(); al.add(e);'而不是整个内部'while'循环。 – 2009-11-20 06:59:04
或者在内部'while'之前设置'count = 0;'。 – 2009-11-20 07:01:25