简体   繁体   中英

I can't figure out what's wrong with comparing array indexes

I need to compare array indexes, not their meanings. I'm a newbie in java at all, and wrote this code and can't understand what exactly I'm doing wrong. Pls 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();
            }
        }
    }

}

Please see my comments. Make sure you close the scanner and assign the variables outside the loop. I am not sure when you want the evaluation to take place, but it seems like it should not happen on every loop. I think you only want the end result, no?

 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(); } } }

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM