計算平均我得到從數組列表
sum = sum + arr[i]; // "i cannot be resolved to a variable"
爲什麼是一個錯誤?
「我」是早些時候宣佈,我嘗試使用值arr[i]
找到並從文本文件一個ArrayList的平均稱爲numbers.txt
public class Statistics {
public static void main(String[] args) {
int [] numbers = readFiles("./bin/q1/numbers.txt");
System.out.println(Arrays.toString(numbers));
}
private static int[] readFiles(String file) {
try {
File f = new File(file);
Scanner s = new Scanner(f);
int ctr = 0;
//counting number of integers in numbers.txt
while (s.hasNextInt()) {
ctr++;
s.nextInt();
}
int [] arr = new int[ctr];
Scanner s1 = new Scanner(f);
//reads integers from file and assigns it to array
for (int i = 0; i < arr.length; i ++)
arr[i] = s1.nextInt();
int sum = 0;
sum = sum + arr[i];
float average = sum/(float) arr.length;
System.out.println("average of array is: " + average + "\n");
System.out.println("length of array is: " + arr.length + " integers \n");
return arr;
}
catch (Exception e) {
return null;
}
}
};
請添加您正在編碼的語言。此外,你還沒有聲明'i',因爲你提到的'i'只存在於'for循環'中,它會在for循環之後被銷燬。取決於你想做什麼,你可以聲明另一個'for-loop',聲明另一個'i',或者用***大括號***將你的代碼包含在以前的for循環中。 – Prisoner
在java中編碼和你的意思是在for循環中包含以前的代碼? – Rgoat