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
}
`
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 oflist1
to another arraylistSizes[]
instead ofnum
used in your code. After reading all the lines if you need it in 2 arrays you can move it easily fromlist1
.Code
Output