我正在尝试编写一些代码来扫描输入文件中的回文,但它从每个单词而不是每行获取字符串。举个例子,赛车会显示为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;
}
}
}发布于 2013-12-02 08:10:00
您需要进行以下更改
变化
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()将读取一行。
发布于 2013-12-02 08:16:24
要从文件中读取行,应该使用nextLine()方法,而不是next()方法。
两者之间的区别是
nextLine() -使此扫描器前进到当前行,并返回跳过的输入。
而
next () -查找并返回此扫描程序中的下一个完整令牌。
因此,您必须更改while语句,使其包含nextLine(),使其如下所示。
while (inputScanner.hasNextLine()) and dirtyString = inputScanner.nextLine();发布于 2014-06-16 00:53:09
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);
}上面的代码段逐行读取文件中的输入,如果不清楚,则返回please see this for complete program code
https://stackoverflow.com/questions/20318872
复制相似问题