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 3 years have passed since last update.

【Java】【Ruby】配列内の偶数を数える

Posted at

 とても簡単ですが、RubyとJavaで、配列内の偶数を数えるプログラムを作りました。「配列を引数として渡すにはどうしたら良いのだろう」という疑問からひとまず作ったものです。

Ruby

def count_evens(nums)
  count = 0
  nums.each do |num|
    if num.even?
      count += 1
    end     
  end
  puts count
end

count_evens([2, 1, 7, 8, 2, 3, 4])
count_evens([2, 2, 6, 5, 0]) 
count_evens([1, 3, 11, 5])

Java

  • メソッドを定義したクラス
package example;

public class CountNums {
	void countEvens(int[] nums) {
		int count = 0;
		for(int num : nums) {
			if (num % 2 == 0) {
				count++;
			}
		}
		System.out.println(count);
	}

}
  • メソッドを呼び出すクラス
package example;

public class UseCountEvens {
	public static void main(String[] args) {
		CountNums n = new CountNums();
		int[] nums1 = {2, 1, 7, 8, 2, 3, 4};
		int[] nums2 = {2, 2, 6, 5, 0};
		int[] nums3 = {1, 3, 11, 5};
		
		n.countEvens(nums1);
		n.countEvens(nums2);
		n.countEvens(nums3);
	}

}

 以上です。

0
0
4

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?