我无法弄清楚比较数组索引有什么问题



我需要比较数组索引,而不是它们的含义。我是java的新手,写了这段代码,不能理解我到底做错了什么。请hlp。

public class Solution {
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
int[] numOfPeople = new int[15];
for (int i = 0; i < numOfPeople.length; i++) {
numOfPeople[i] = scanner.nextInt();

int sum2 = 0;
int sum1 = 0;

if (i % 2 == 0) {
sum2 = sum2 + numOfPeople[i];
} else if (i % 2 != 0) {
sum1 = sum1 + numOfPeople[i];
}

if (sum2 > sum1) {
System.out.println("В домах с четными номерами проживает больше жителей.");
} else if (sum2 < sum1) {
System.out.println("В домах с нечетными номерами проживает больше жителей.");
} else {
System.out.println();
}
}
}

}

请看我的评论。确保关闭扫描程序并在循环外赋值变量。我不确定您希望何时进行评估,但似乎不应该在每个循环中都进行评估。我觉得你只想要最后的结果,不是吗?

import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
int[] numOfPeople = new int[15];
//I think you want these to be available outside the loop and not modified every iteration of the loop
int sum2 = 0;
int sum1 = 0;
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < numOfPeople.length; i++) {
//I added this just to help you see the iteration
System.out.println("You must enter the value for index i: " + i);
numOfPeople[i] = scanner.nextInt();

//I think you mean to know if the index is even or odd here 
if (i % 2 == 0) {
sum2 = sum2 + numOfPeople[i];
} else if (i % 2 != 0) {
sum1 = sum1 + numOfPeople[i];
}
} // I think you want to close the loop here, because you do not want this evaluated every time you go to a new index, but rather at the end?
scanner.close();
if (sum2 > sum1) {
System.out.println("Even has more occupancy");
} else if (sum2 < sum1) {
System.out.println("Odd has more occupancy");
} else {
System.out.println();
}
}
}

最新更新