0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Javaの配列での複数を求める場合

Last updated at Posted at 2020-05-18

【例】

Main.java
class Main {
  public static void main(String[] args) {
    int[] numbers = {1, 6, 11, 16, 21, 26};
    
    int oddNumber = 0;
    int evenNumber = 0;
    
    for (int number : numbers) {
      if (number % 2 == 0) {
        evenNumber += number;
      } else {
        oddNumber += number;
      }
    }

    System.out.println("奇数の合計は" + oddNumber + "です");
    System.out.println("偶数の合計は" + evenNumber + "です");
  }
}

上記の結果は奇数の合計は33です
偶数の合計は48です
となります。
配列numbersの要素を1つずつ取得し、その要素の値が
奇数であれば変数oddNumberで
偶数であれば変数evenNumberとしています。
偶数であるか奇数であるかの判定は、if文で「%」を用いています。
「% 2 == 0」とすることでk「evenNumber += number;」で偶数であるか
違えばelseの「oddNumber += number;」が実行されます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?