user2891092
user2891092

Reputation: 163

java - how to read line on specific side of paragraph

Hi so i have this project that want 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 read the left side of the text (goodtitle,gold,wheat,wood,etc). 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();
            System.out.printf("%s \n", a);
        }
    }
    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.

Upvotes: 0

Views: 426

Answers (1)

user1231232141214124
user1231232141214124

Reputation: 1349

public void readFile(){
    while (x.hasNextLine()){
        String a = x.next();
        x.nextLine();
        System.out.printf("%s \n", a);
    }
}

You just need to move on to the next line after reading in the first token. You were almost there!

x.nextLine() will move the scanner to the next line. x.next() will keep reading in tokens, which in this case is a string of letters split by spaces (eg. words), until it reaches the end of the line.

Upvotes: 1

Related Questions