简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM