[英]not storing text data into java array using scanner
我的代碼只是打印出我在其他程序中創建的列表中的最后一個數字。 我需要將數據存儲到數組中的幫助,以便以后對其進行排序。 編輯:我需要從文件“ numbers.txt”中獲取數據並將其存儲到數組中。
public static void main(String[] args) throws Exception {
int numberArray = 0;
int[] list = new int[16];
File numbers = new File("numbers.txt");
try (Scanner getText = new Scanner(numbers)) {
while (getText.hasNext()) {
numberArray = getText.nextInt();
list[0] = numberArray;
}
getText.close();
}
System.out.println(numberArray);
int sum = 0;
for (int i = 0; i < list.length; i++) {
sum = sum + list[i];
}
System.out.println(list);
}
}
代碼中的更正。
1.)在while循環中, list[0] = numberArray;
,將繼續在相同的index 0
上添加元素,因此lat值將被覆蓋。 所以像list[i] = numberArray;
將工作,並在while loop
increement i
。 在這里照顧ArrayIndexOutOfBound Exception
。
public static void main(String[] args) throws Exception {
int numberArray = 0;
int[] list = new int[16];
File numbers = new File("numbers.txt");
int i =0;
// Check for arrayIndexOutofBound Exception. SInce size is defined as 16
try (Scanner getText = new Scanner(numbers)) {
while (getText.hasNext()) {
numberArray = getText.nextInt();
list[i] = numberArray;
i++;
}
getText.close();
}
System.out.println(numberArray);
int sum = 0;
for (int i = 0; i < list.length; i++) {
sum = sum + list[i];
}
System.out.println(list);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.