【问题标题】:How do I turn a text line of integers into an array of integers?如何将整数文本行转换为整数数组?
【发布时间】:2012-04-19 21:45:57
【问题描述】:

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

Jill

5 0 0 0

Suave

5 5 0 0

Mike

5 -5 0 0

Taj

3 3 5 0

我已成功地将名称转换为字符串数组列表,但我希望能够读取每隔一行并将其转换为整数数组列表,然后制作这些数组列表的数组列表。这就是我所拥有的。我觉得它应该可以工作,但显然我做的不对,因为我的整数数组列表中没有任何内容。

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

        }

【问题讨论】:

    标签: java


    【解决方案1】:

    这不起作用,因为您在检查它是 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));
    

    【讨论】:

    • 非常感谢!出于好奇,为什么您的第二个建议更好?
    • 可能应该允许带有line.split(" +") 的数字之间有多个空格或带有line.split("\\s+") 的任何空格(记住要拆分的arg 是一个正则表达式)
    • 另外,如何让它在完成该行后停止读取整数?无论如何要放入while布尔值(直到换行符)或类似的东西?编辑没关系。我想通了。
    猜你喜欢
    • 1970-01-01
    • 2011-04-04
    • 1970-01-01
    • 2021-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多