0

嗨所以我有这个项目希望我用 java 编写代码可以说我有这个 txt 文件:

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

我要做的就是阅读文本的左侧(好标题、黄金、小麦、木材等)。这是我当前的代码:

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();

可能它需要对 readFile 进行一些修改,因为我仍然对如何做到这一点感到困惑。提前致谢...

注意=我不允许更改 txt 文件的内容。

4

1 回答 1

1
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.

于 2013-10-17T15:23:31.953 回答