繁体   English   中英

如何将整数文本行转换为整数数组?

[英]How do I turn a text line of integers into an array of integers?

我有一个文本文件,其中一半行是名称,每隔一行是一系列用空格分隔的整数:

Jill

5 0 0 0

Suave

5 5 0 0

Mike

5 -5 0 0

Taj

3 3 5 0

我已经成功地将名称转换为字符串数组列表,但是我希望能够读取每隔一行并将其转换为整数数组列表,然后创建这些数组列表的数组列表。 这就是我所拥有的。 我觉得应该可以,但是很显然我做的不好,因为没有东西可以填充我的整数数组列表。

rtemp是单行整数的数组列表。 allratings是arraylists的arraylist。

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);  
            }

        }

这是行不通的,因为您在检查该行是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));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM