【问题标题】:Get all words from text file (Java)从文本文件中获取所有单词(Java)
【发布时间】:2019-04-15 17:02:10
【问题描述】:

我正在尝试显示文件中可以水平和垂直找到的所有单词,并且我正在尝试打印每个单词(行和列)的第一个字符的位置。

我让它水平显示每个单词而不是垂直显示。

这是我目前使用的代码

public class WordFinder {
    public static final String WORD_FILE = "words.txt";
    public static void find(){
        try {
            File file = new File(WORD_FILE);
            Scanner scanner = new Scanner(file);
            while (scanner.hasNext() == true) {
                String s = scanner.next();
                System.out.println(s);
            }
            scanner.close();
        } catch (FileNotFoundException e) {
            System.out.println("File not found.");
    }
}

它应该水平和垂直搜索文件以查找单词。一旦找到一个单词,它应该显示该单词的第一个字母的位置(例如grammar: row 8, position 1)目前它只打印所有水平单词。

【问题讨论】:

  • char[][] 中输入words.txt 的行,然后实现在char[][] 中搜索单词的函数。你可以使用String.toCharArray()
  • 每一行的长度都一样吗?
  • 所有行的长度不同

标签: java file loops java.util.scanner word


【解决方案1】:

您必须在迭代时计算单词的行号和位置。因此您应该使用scanner.hasNextLine()scanner.nextLine()。之后就可以分行了:

int lineNumber = 0;
while (scanner.hasNextLine()) {
    String line = scanner.nextLine();
    int positionNumber = 0;
    for (String word : line.split("\\s")) {
        if (!word.isEmpty())
            System.out.println(word + ": line " + (lineNumber + 1) + ", position " + (positionNumber + 1));
        positionNumber += word.length() + 1;
    }
    lineNumber++;
}

这会在所有空格 (\\s) 上拆分行,并使用 if (!word.isEmpty()) 处理双空格(空字)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-27
    • 2017-08-30
    • 1970-01-01
    • 2012-10-18
    • 2021-02-11
    • 1970-01-01
    相关资源
    最近更新 更多