gpt4 book ai didi

java - 逐行而不是逐字阅读文件

转载 作者:搜寻专家 更新时间:2023-11-01 02:46:46 25 4
gpt4 key购买 nike

我正在尝试编写一些代码来扫描输入文件中的回文,但它从每个单词而不是每一行中获取字符串。一个例子是赛车会显示为 racecar= palindrome 或 too hot to hoot = palindrome 但相反它会 go too= not a palindrome, hot= not a palindrome 等。

这是我目前正在做的读取文件的操作

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() 将读取下一个标记

inputScanner.nextLine() 将读取一行。

关于java - 逐行而不是逐字阅读文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20318872/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com