user2891092 user2891092 - 2 months ago 6
Java Question

JAVA - how to read specific line then put it in arraylist

Hi so i have this project that requires me to write the code in java lets say i have this txt file:

GoodTitle Description
Gold The shiny stuff
Wheat What wheaties are made of
Wood To make more ships
Spices To disguise the taste of rotten food
Tobacco Smoko time
Coal To make them steam ships go
Coffee Wakes you up
Tea Calms you down


all i want to do is to put the left side of the text (goodtitle,gold,wheat,wood,etc) into an arraylist and the right side of the text(description,the shiny stuff) into another array list. this is my current code:

public void openFile(){
try{
x = new Scanner(new File("D://Shipping.txt"));
}
catch (Exception e){
System.out.println("File could not be found");
}
}
public void readFile(){
while (x.hasNextLine()){
String a = x.next();
x.nextLine();
ArrayList<String> list = new ArrayList<String>();
while (x.hasNext()){
list.add(x.next());
}
System.out.printf("%s \n", list);
}
}
public void closeFile(){
x.close();


probably it need some modification on readFile as i still confuse on how to do it. thanks in advance...

NOTE=I am not allowed to change the content of the txt file.
in my current code i still put the whole thing into 1 arraylist because i am unable to split them.


do i need toString method?because i have no idea how to do it.
thanks in advance...

Answer

You have to read the left side into one list and the right side into another.

This code isn't right because x.next() doesn't actually return one column. How could it know what one column is? But it should give you an idea of how to do it.

ArrayList<String> listL = new ArrayList<String>();
ArrayList<String> listR = new ArrayList<String>();
while (x.hasNextLine()){
    x.nextLine();
    if (x.hasNext()){
        listL.add(x.next());
    } else {
        listL.add("");
    }

    if (x.hasNext()){
        listR.add(x.next());
    } else {
        listR.add("");
    }
}
System.out.println(listL);
System.out.println(listR);