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. 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. 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. 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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.