reading a text file line by line and putting the lines into lists in Java

190 views Asked by At

If I had the following text file:

5 -5 -4 -3 -2 -1

6 -33 -22 -11 44 55 66

(the first # in line is the length of the list)

How do I read the file line by line and then read the integers in each of the lines to create 2 lists?

Desired output of program:

list1 = [-5,-4,-3,-2,-1]
list2 = [-33,-22,-11,44,55,66]

The following is the what I was able to do to get one line done but i dont know how to modify it to continue reading the lines.

import java.util.*;
import java.io.*;
import java.io.IOException;
public class Lists 
{
   public static void main(String[] args) throws IOException // this tells the compiler that your are going o use files
   {     
         if( 0 < args.length)// checks to see if there is an command line arguement 
         {
            File input = new File(args[0]); //read the input file


            Scanner scan= new Scanner(input);//start Scanner

            int num = scan.nextInt();// reads the first line of the file
            int[] list1= new int[num];//this takes that first line in the file and makes it the length of the array
            for(int i = 0; i < list1.length; i++) // this loop populates the array scores
            {

               list1[i] = scan.nextInt();//takes the next lines of the file and puts them into the array
            }

`

1

There are 1 answers

2
Johny On

I have made list1 to be a 2d array which will be having each of the line as its rows. I am storing the no. of elements of each of the rows of list1 to another array listSizes[] instead of num used in your code. After reading all the lines if you need it in 2 arrays you can move it easily from list1.

Code

int listSizes[] = new int[2];
int[][] list1= new int[2][10];
for(int j = 0; scan.hasNextLine(); j++) {
    listSizes[j] = scan.nextInt();
    for(int i = 0; i < listSizes[j]; i++) 
    {
       list1[j][i] = scan.nextInt();
    }
}
for(int j = 0; j < 2; j++) {

    for(int i = 0; i < listSizes[j]; i++) 
    {
       System.out.print(list1[j][i] + " ");
    }
    System.out.println();
}

Output

-5 -4 -3 -2 -1 
-33 -22 -11 44 55 66