Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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

        }
like image 367
WAMoz56 Avatar asked Dec 02 '25 19:12

WAMoz56


1 Answers

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));
like image 122
Jack Avatar answered Dec 05 '25 08:12

Jack



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!