3 回答

TA貢獻1824條經驗 獲得超5個贊
讓我們分解一下:
這將讀取輸入文件的每一行,計算每一行,然后丟棄它們:
while(reader.hasNextLine()) { reader.nextLine(); lineCount++; }
您現在位于文件末尾。
分配一個足夠大的字符串數組。
String[] bookArray = new String[lineCount];
嘗試閱讀更多行。循環將立即終止,因為
reader.hasNextLine()
將返回false
。您已經在文件末尾。所以你分配給的語句
bookArray[i]
不會被執行。while (reader.hasNextLine()) { for (int i = 0; i < lineCount; i++) { bookArray[i] = reader.next(); } }
由于
bookArray[i] = ...
上面從未執行過,所有數組元素仍將是null
.for (int k = 0; k < lineCount; k++) { System.out.println(bookArray[k]); }
一種解決方案是打開并讀取文件兩次。
另一種解決方案是將文件“重置”回開頭。(有點復雜。)
另一種解決方案是使用 aList
而不是數組,這樣您就不需要讀取文件兩次。
另一種解決方案是在 javadoc 中搜索一種方法,該方法會將文件/流的所有行讀取為字符串數組。
(其中一些可能會因您的練習要求而 被排除。您將其解決...)
第3步的嵌套循環也是錯誤的。您不需要在 while 循環中使用 for 循環。您需要一個循環來“遍歷”行并遞增數組索引 ( i
)。它們不需要都由循環語句本身來完成。您可以在循環體中執行一個或另一個(或兩個)。

TA貢獻1890條經驗 獲得超9個贊
您試圖在文件中循環兩次,但您已經在第一次到達文件末尾。不要循環兩次。將兩個 while 循環“合并”為一個,刪除 while 循環內的 for 循環并收集所有書名。然后您可以使用列表的大小稍后打印它們。我的 Java 可能生銹了,但它在這里 -
import java.io.*;
import java.util.*;
public class LibraryInputandOutputs {
? ? public static void main(String args[]) throws IOException {
? ? ? ? // int lineCount = 0; - You don't need this.
? ? ? ? File inputFile = new File("bookTitles.inp.txt");
? ? ? ? Scanner reader = new Scanner(inputFile);
? ? ? ? // Use an array list to collect book titles.
? ? ? ? List<String> bookArray = new ArrayList<>();?
? ? ? ? // Loop through the file and add titles to the array list.
? ? ? ? while(reader.hasNextLine()) {
? ? ? ? ? ? bookArray.add(reader.nextLine());
? ? ? ? ? ? // lineCount++; - not needed
? ? ? ? }
? ? ? ? // Not needed -
? ? ? ? // while (reader.hasNextLine()) {
? ? ? ? //? ? ?for (int i = 0; i < lineCount; i++) {
? ? ? ? //? ? ? ? ?bookArray[i] = reader.next();
? ? ? ? //? ? ? }
? ? ? ? // }
? ? ? ? // Use the size method of the array list class to get the length of the list?
? ? ? ? // and use it for looping.
? ? ? ? for (int k = 0; k < bookArray.size(); k++) {??
? ? ? ? ? ? System.out.println(bookArray[k]);
? ? ? ? }
? ? ? ? reader.close();
? ? ? ? inputFile.close();
? ? }
}

TA貢獻1776條經驗 獲得超12個贊
特別是,使用 List 通常比使用數組更好,因為它更靈活。如果你需要一個數組,你總是可以在 List 被填充后使用 toArray() 。
你的書名是分開的嗎?如果是這樣,您可能不需要 Scanner 類,可以使用 BufferedReader 或 LineNumberReader 之類的東西。
添加回答
舉報