![](/img/trans.png)
[英]I've added things into my ArrayList but still not working for loop, and function
[英]My arraylist size is a zero even though I've added items to the it
所以我嘗試查找此錯誤( Exception in thread "main" java.lang.ArithmeticException: / by zero
)並認為下面代碼中的 arraylist 大小為零。 我不明白為什么它為零或如何解決它。 它必須對陣列的容量做些什么嗎? 我似乎無法弄清楚我的代碼有什么問題。
順便說一句,此代碼用於計算 arraylist 中所有元素的平均值,並讓用戶知道平均值是多少。
我仍然是 Java 的初學者,所以如果這看起來很愚蠢,我深表歉意。 任何幫助表示贊賞!
import java.util.*;
public class ClassStuff {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList <Integer> myArray = new ArrayList <Integer> ();
int userInput = 0;
String userConf = "";
while ((!userConf.equalsIgnoreCase("y"))) {
System.out.println("Please enter a number: ");
userInput = scan.nextInt();
for (int i = 1; i <= myArray.size(); i++) {
userInput = scan.nextInt();
myArray.add(userInput);
}
scan.nextLine();
System.out.println("Are you done entering numbers? (y/n): ");
userConf = scan.nextLine();
}
int result = computeAvg(myArray);
System.out.println("Average is: " + result);
}
public static int computeAvg(List <Integer> myArray) {
int sum = 0;
int avg = 0;
for (int i = 0; i < myArray.size(); i++) {
sum = sum + myArray.get(i);
}
return avg = sum/myArray.size();
}
}
我假設這些行:
System.out.println("Please enter a number: ");
userInput = scan.nextInt();
獲取要添加到 arraylist 中的元素數量,我們稍后通過 for 循環將其添加到列表中。 在這種情況下,將其保存在另一個名為list_length
的變量中,因為userInput
在 for 循環中不斷變化。
System.out.println("Please enter a number: ");
list_length = scan.nextInt();
然后將此輸入后的 for 循環更改為:
for(int i = 1; i <= list_length; i++) {
userInput = scan.nextInt();
myArray.add(userInput);
}
這是因為您將 for 循環的結尾更改為myArray.size()
,但請記住它已經是 0,因此 for 循環從1 >= 0
開始結束。 您可能想要做的是將list_length
數量的數字添加到 arraylist
我發現了你的問題。
問題出在你的 for 循環上,因為 arrayList 在循環期間沒有捕捉到任何元素。
我還對該方法進行了一些調整,以便計算平均值。
這是一個例子
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList <Integer> myArray = new ArrayList<>();
int userInput = 0;
String userConf = "";
while ((!userConf.equalsIgnoreCase("y"))) {
System.out.println("Please enter a number: ");
userInput = scan.nextInt();
myArray.add(userInput);
scan.nextLine();
System.out.println("Are you done entering numbers? (y/n): ");
userConf = scan.nextLine();
}
System.out.println(myArray);
double result = computeAvg(myArray);
System.out.println("Average is: " + result);
}
public static double computeAvg(List <Integer> myArray) {
double sum = 0;
double avg = 0;
for (int i = 0; i < myArray.size(); i++) {
sum = sum + myArray.get(i);
}
avg = sum / myArray.size();
return avg;
}
Output
我的列表 = [4,5]
平均值 = (4 + 5) / 2 (myArray.size())= 4.5
希望它有用!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.