逐行读取文件而不是逐个单词读取

4
我正在尝试编写一些代码来扫描输入文件中的回文,但它从每个单词获取字符串而不是每行。例如,racecar将显示为racecar = 回文或too hot to hoot = 回文,但实际上它会变成too = 不是回文,hot = 不是回文等。
以下是我目前用于读取文件的方法:
File inputFile = new File( "c:/temp/palindromes.txt" );
Scanner inputScanner = new Scanner( inputFile );
while (inputScanner.hasNext())
{
    dirtyString = inputScanner.next();

    String cleanString = dirtyString.replaceAll("[^a-zA-Z]+", "");

    int length  = cleanString.length();
    int i, begin, end, middle;

    begin  = 0;
    end    = length - 1;
    middle = (begin + end)/2;

    for (i = begin; i <= middle; i++) {
        if (cleanString.charAt(begin) == cleanString.charAt(end)) {
            begin++;
            end--;
        }
        else {
            break;
        }
    }
}

3
你读过 Scanner API 吗?也许这个方法可以解决 Scanner#nextLine() 的问题。 - nachokk
读取文件?我肯定会使用BufferedReader - Justin
你应该始终格式化你的代码。我对它进行了编辑,由于代码不完整,我不得不假设你想添加两个 }。如果你格式化你的代码,你就能找到这样的错误。 - Justin
3个回答

3
您需要进行以下更改:
更改:
while (inputScanner.hasNext()) // This will check the next token.

and 

dirtyString  = inputScanner.next(); // This will read the next token value.

为了

while (inputScanner.hasNextLine()) // This will check the next line.

and dirtyString = inputScanner.nextLine(); // This will read the next line value.

inputScanner.next()将读取下一个标记。

inputScanner.nextLine()将读取单行。


1

要从文件中读取一行,您应该使用nextLine()方法而不是next()方法。

两者之间的区别是

nextLine() - 将此扫描器推进到当前行并返回跳过的输入。

next() - 从此扫描器查找并返回下一个完整标记。

所以您需要更改while语句以包括nextLine(),它看起来像这样。

while (inputScanner.hasNextLine()) and dirtyString = inputScanner.nextLine();

0
FileReader f = new FileReader(file);
BufferedReader bufferReader = new BufferedReader(f);
String line;
//Read file line by line and print on the console
while ((line = bufferReader.readLine()) != null)   {
        System.out.println(line);
}

上述代码段逐行从文件中读取输入,如果不清楚的话,请参考完整的程序代码


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接