[英]having trouble finding the sum of my array JAVA
while (file.hasNext()) {
if (file.hasNextInt()) {
int readMidGrades = file.nextInt();
int readFinalGrades = file.nextInt();
int[] midterms = {readMidGrades};
int[] finals = {readFinalGrades};
double sum = 0;
for(int i=0; i<midterms.length; i++) {
sum += midterms[i];
}
double average=(sum/midterms.length);
System.out.print(average);
So, i am trying to find the sum of my array.所以,我试图找到我的数组的总和。 I have made two int arrays, i received the numbers from a file.
我制作了两个 int 数组,我从文件中收到了数字。 When try to get the sum it prints out the numbers but does not sum them.
当尝试求和时,它会打印出数字但不会对它们求和。 I am writing it exactly how my textbook says and even other ways i have found on here.
我写的正是我的教科书所说的,甚至是我在这里找到的其他方式。 I would like to keep the for loop that I have.
我想保留我拥有的 for 循环。 Is this happening because it is saving the numbers as a string??
这是因为它将数字保存为字符串吗?
For now you have two arrays of one element, both reinitialize every time in your loop (also I think there are missing parenthesis).现在你有两个一个元素的数组,每次在你的循环中都重新初始化(我也认为缺少括号)。
Consider using of ArrayList for readMidGrades and readFinalGrades values storage.考虑将ArrayList用于readMidGrades和readFinalGrades值存储。 So your code should look like that:
所以你的代码应该是这样的:
List<Integer> midterms = new ArrayList<>();
List<Integer> finals = new ArrayList<>();
while (file.hasNext()) {
if (file.hasNextInt()) {
int readMidGrades = file.nextInt();
int readFinalGrades = file.nextInt();
midterms.add(readMidGrades);
finals.add(readFinalGrades);
}
}
double sum = 0;
for(int i=0; i<midterms.size(); i++) {
sum += midterms.get(i);
}
double average=(sum/midterms.size());
System.out.print(average);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.