[英]Reading File by line instead of word by word
我正在嘗試編寫一些掃描輸入文件中的回文的代碼,但它從每個單詞而不是每一行獲取字符串。 一個例子是賽車將顯示為賽車=回文或太熱而不是hoot =回文,但它也會變得太過=不是回文,熱=不是回文等。
這是我正在做的目前讀取文件
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()將讀取一行。
要從文件中讀取一行,您應該使用nextLine()methond而不是next()方法。
兩者的區別在於
nextLine() - 使此掃描程序超過當前行並返回跳過的輸入。
而
next() - 查找並返回此掃描程序中的下一個完整標記。
因此,您必須更改while語句以包含nextLine(),因此它看起來像這樣。
while (inputScanner.hasNextLine()) and dirtyString = inputScanner.nextLine();
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);
}
上面的代碼段逐行讀取文件中的輸入,如果不清楚, 請查看完整的程序代碼
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.