-2

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
            }

`

us42
  • 1
  • 1
  • It would be good if you add the code that you have tried. – Johny Nov 24 '14 at 02:35
  • When asking a question on Stack Overflow, you need to provide evidence of research and attempts you have already made to resolve the problem. Questions that consist of "I don't know what to do, can someone help me" are not acceptable on Stack Overflow. You need to provide a [Minimum, complete, verifiable example](http://stackoverflow.com/help/mcve) of your problem. – simo.3792 Nov 24 '14 at 02:40
  • Are my edits acceptable? – us42 Nov 24 '14 at 02:49

1 Answers1

0

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 
Johny
  • 2,128
  • 3
  • 20
  • 33
  • I need them to be 2 separate arrays so I can merge them and do other things later in the program – us42 Nov 24 '14 at 03:26
  • @us42 you can copy each row of the 2d array into separate arrays after reading if you need. – Johny Nov 24 '14 at 03:36