阅读java中的下一个单词 [英] Read next word in java

查看:172
本文介绍了阅读java中的下一个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含以下内容的文本文件:

I have a text file that has following content:

ac und
accipio annehmen
ad zu
adeo hinzugehen
...

我读了文本文件并迭代通过以下行:

I read the text file and iterate through the lines:

Scanner sc = new Scanner(new File("translate.txt"));
while(sc.hasNext()){
 String line = sc.nextLine();       
}

每行有两个单词。 java中是否有任何方法可以获取下一个单词,还是必须拆分行字符串以获取单词?

Each line has two words. Is there any method in java to get the next word or do I have to split the line string to get the words?

推荐答案

您不一定要拆分该行,因为java.util.Scanner的默认分隔符是空格。

You do not necessarily have to split the line because java.util.Scanner's default delimiter is whitespace.

您可以在while语句中创建一个新的Scanner对象。

You can just create a new Scanner object within your while statement.

    Scanner sc2 = null;
    try {
        sc2 = new Scanner(new File("translate.txt"));
    } catch (FileNotFoundException e) {
        e.printStackTrace();  
    }
    while (sc2.hasNextLine()) {
            Scanner s2 = new Scanner(sc2.nextLine());
        while (s2.hasNext()) {
            String s = s2.next();
            System.out.println(s);
        }
    }

这篇关于阅读java中的下一个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆