2012-04-19 236 views
2

我有一个文本文件,在其中一半的线名和所有其他行是一系列整数用空格分隔:如何将整数文本行转换为整数数组?

Jill 

5 0 0 0 

Suave 

5 5 0 0 

Mike 

5 -5 0 0 

Taj 

3 3 5 0 

我已经成功地变成了名称为字符串的ArrayList,但我d喜欢能够读取其他所有行并将其转换为整数列表,然后制作这些列表的数组列表。这是我的。我觉得它应该工作,但显然我没有做正确的事,因为没有填充我的数组列表的整数。

rtemp是一行整数的数组列表。 allratings是阵列列表的阵列列表。

while (input.hasNext()) 
     { 

      count++; 

      String line = input.nextLine(); 
      //System.out.println(line); 

      if (count % 2 == 1) //for every other line, reads the name 
      { 
        names.add(line); //puts name into array 
      } 

      if (count % 2 == 0) //for every other line, reads the ratings 
      { 
       while (input.hasNextInt()) 
       { 
        int tempInt = input.nextInt(); 
        rtemp.add(tempInt); 
        System.out.print(rtemp); 
       } 

       allratings.add(rtemp); 
      } 

     } 

回答

4

这不起作用,因为您在检查它是否是String行或int行之前先读取行。所以当你打电话给nextInt()时,你已经超过了数字。

你应该做的是移动String line = input.nextLine();第一种情况中,或者甚至更好,直接行工作:

String[] numbers = line.split(" "); 
ArrayList<Integer> inumbers = new ArrayList<Integer>(); 
for (String s : numbers) 
    inumbers.add(Integer.parseInt(s)); 
+0

太谢谢你了!出于好奇,为什么你的第二个建议更好? – WAMoz56 2012-04-19 22:03:47

+0

可能应该允许多个空格之间的数字与''line.split(“+”)''或任何空格与''line.split(“\\ s +”)''(记住arg拆分是一个正则表达式) – sw1nn 2012-04-19 22:13:45

+0

也,如何在使用该行时停止读取整数?无论如何要放置boolean(直到换行符)或什么的效果?编辑没关系。我想到了。 – WAMoz56 2012-04-19 22:19:18