2 回答

TA貢獻(xiàn)1777條經(jīng)驗(yàn) 獲得超3個贊
在用元素填充數(shù)組之前,您正在打印數(shù)組。
您的計(jì)數(shù)器在循環(huán)的每次迭代中都
i
重置為。雖然使用具有固定數(shù)量元素的數(shù)組來讀取未知長度的文本不是一個好主意,但還是使用一些動態(tài)數(shù)組,例如.0
while
ArrayList
確保您提供了正確的
.txt
文件路徑。
所以你的代碼可能是這樣的:
Scanner sc = new Scanner(new File ("C:/correct/path/to/file/master_file.txt"));
List<String> listOfStrings = new ArrayList<String>();
while(sc.hasNextLine()) {
listOfStrings.add(sc.nextLine());
}
System.out.println(listOfStrings);

TA貢獻(xiàn)1784條經(jīng)驗(yàn) 獲得超7個贊
輸出為空,因?yàn)樵趪L試打印數(shù)組之前您從未分配過任何數(shù)組。我還將 i 移到循環(huán)之外,因此每次都不會重新初始化。此外,由于 ids 是一個數(shù)組,您需要使用 Arrays.toString(ids) 來打印它,或者您只需獲取對象 id。
public static void main(String[] args) throws FileNotFoundException {
String[] ids = new String[100]; //array to store lines
int i = 0; // line index
try (Scanner sc = new Scanner(new File ("master file.txt"))) { // try resource
while(sc.hasNextLine()) { // check for next line
ids[i] = sc.nextLine(); // store line to array index
i++; // increment index
}
}
System.out.println(Arrays.toString(ids)); //print output.
}
添加回答
舉報(bào)