Home>

I'm learning hands-on programming, but I don't understand the theory of the answer source code. Can you tell me why you can do this?

Challenges: Pick up odd numbers and even numbers, and give each sum

I interpreted my source code in bold.

class Main {
public static void main (String [] args) {
// Substitute the given number array for the variable numbers
int [] numbers = {1, 4, 6, 9, 13, 16};

int oddSum = 0;
int evenSum = 0;

// Use the for statement to find the even and odd sums of the array numbers
for (int number: numbers) { if (number% 2 == 0) {// ← if divisible by 2
evenSum + = number;
Addition of variables to evenSum **
} else {// ← otherwise
oddSum + = number;** // Add variable to oddSum **
// I think this source code will add all the functions even if branching with evenSum and oddSum, where is the number changing from even to odd?
}
}

// ---- Without extended for statement ----
// for (int i = 0;i // if (numbers [i]% 2 == 0) {
// evenSum + = numbers [i];
//} else {
// oddSum + = numbers [i];
//}
//}

System.out.println ("Odd sum is" + oddSum + "");
System.out.println ("The even sum is" + evenSum + "");
}
}

  • Answer # 1

    for (int number: numbers) {
      if (number% 2 == 0) {
        evenSum + = number;
      } else {
        oddSum + = number;
      }
    }

    If the variable for which you want to loop out elements is an array, you can understand that if you write as above, the java compiler will generate the following bytecode (create a .class file) think.

    for (int i = 0;i

    Because the first line of this is a regular form when the elements of the array are extracted and processed from the beginning to the end, this is a simplified grammar (may be expressed as syntax, sugar, etc.) Added) in Java SE 5.
    In that grammar, a variable that assigns each element extracted by subscript is declared in the formfor (int number:, so that it is not necessary to refer to the array using subscript.
    By doing this, the amount of code to be written is reduced, and it also has the effect of preventing bugs caused by the handling of subscript variables (such as changing the value during a loop).

  • Answer # 2

    numberin an extended for statement indicates the same value asnumbers [i]in a non-extended for statement.
    for (int number: numbers)means thatnumberis assigned one element at a time and{}is performed.
    For example, whennumber= 4,if (number% 2 == 0)passes, soevenSum + = number;Will be executed, butoddSum + = number;will not be executed when you pass here, so onlyevenSumwill change andoddSumwill not change It will be.