我正在尝试编写一些代码来扫描输入文件中的回文,但是它从每个单词而不是每一行获取字符串。例如,赛车将显示为racecar =回文,或者太热而无法回响=回文,但是相反,它会太过=非回文,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;
}
}
}
最佳答案
您需要进行以下更改
更改
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()将读取下一个 token
inputScanner.nextLine()将读取一行。