简体   繁体   中英

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

I have a text file in which half the lines are names and every other line is a series of integers separated by spaces:

Jill

5 0 0 0

Suave

5 5 0 0

Mike

5 -5 0 0

Taj

3 3 5 0

I've successfully turned the names into an arraylist of strings, but I'd like to be able to read every other line and turn it into an arraylist of integers and then make an arraylist of those array lists. Here's what I have. I feel that it should work, but obviously I'm not doing something right because nothing populates my array list of integers.

rtemp is an arraylist of a single line of integers. allratings is the arraylist of arraylists.

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

        }

This does not work because you read the line before checking if it was a String line or an int line. So when you call nextInt() you are already over the line with numbers.

What you should do is to move String line = input.nextLine(); inside the first case or, even better, work on the line directly:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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