[英]Reading from a file in java and save the int numbers from the txt in array
[英]Adding Numbers to an Array from a .txt File
嗨我是相當新的java和試圖從一個名為compact.txt號碼添加到一個數組時,我有這個問題。 到目前為止,這是我的代碼:
public void compactArray(){
try{
Scanner scan = new Scanner(new File("compact.txt"));
while(scan.hasNextInt()){
num++;
}
int [] a = new int[num];
Scanner in = new Scanner(new File("compact.txt"));
while(counter < num){
a[counter] = in.nextInt();
counter++;
}
System.out.println(Arrays.toString(a));
}catch(IOException bob){
bob.getMessage();
}
}
這段代碼的問題是,它從未停止運行。 首先,我的代碼讀取compact.txt文件,然后計算它必須計算出數組大小的數量。 然后,我制作另一個掃描程序變量,以將來自compact.txt的數字添加到數組中。 我將計數器變量用作在數組a中添加所需數量的數字時停止的一種方式。 我也不太清楚是什么問題,但它一直在運行,沒有得到的地方,它應該打印出數組行。 有人可以幫幫我嗎。 非常感謝。
你應該打電話
scan.nextInt();
在您的第一個循環中。 您永遠不會移動光標,因此您一直在閱讀第一個元素。
但是,您的解決方案需要遍歷兩次數據集。 您可能要使用ArrayList,它是可以調整大小的數組。 這樣,您無需先計算文件數。
您在此處做錯了什么:為此,您僅應使用一個Scanner
對象。
更具體地講,什么你的情況是怎么了?是這樣的:你是檢查是否掃描器的下一個INT while(scan.hasNextInt()){
,但你從來沒有真正讀取INT。 因此它將永遠循環。
正確的工作代碼為:
public void compactArray(){
List<Integer> ints = new ArrayList<>();
try{
Scanner scan = new Scanner(new File("compact.txt"));
while(scan.hasNextInt()){
ints.add(in.nextInt());
}
}catch(IOException ex){
ex.getMessage();
}
System.out.println(Arrays.toString(ints.toArray(new int[ints.size()])));
}
我還更改了代碼的以下幾點:
List<Integer>
存儲整數。 因此,不再需要進行計數! System.out.println
,現在List<Integer>
將首先被轉換為一個數組,然后將String
-表示中給出。 更改
while(scan.hasNextInt()){ here is the problem, This loop never move to next integer. You need to call to scan.nextInt() required to move next integer
num++;
}
至
while(scan.hasNextInt()){
scan.nextInt();
num++;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.