[英]I need to make permutations with an array using the ArrayList Class. I can't figure out what's wrong
[英]I can't figure out what's wrong with comparing array indexes
我需要比較數組索引,而不是它們的含義。 我根本是java的新手,寫了這段代碼,不明白我到底做錯了什么。 請幫忙。
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(); } } }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.