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】Listに格納した値の平均値を出力

Posted at

ちょっと悩んだのでメモとして。

Average.java
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class Average{
	public static void main(String[] args) {
		
		//Listに値を格納(ランダムで)
		List<Integer> list = new ArrayList<>();
		for(int i=0; i<5; i++) {
			Random random = new Random();
			int randomNum = random.nextInt(101); //0~100
			list.add(randomNum);
		}
		System.out.println(list); //値が格納されているか確認(後で消す) -> 例:[62, 73, 43, 35, 58]
		
		//Listに格納した値の合計
		double sum = 0;
		for(int j=0; j<5; j++) {
			sum += list.get(j);
		}
		System.out.println("合計値:" + sum); //合計の確認(後で消す) -> 例:合計値:271.0
		
		//平均値
		double average = sum / list.size();
		System.out.println("平均値:" + average);
	}
}
実行結果.
[76, 75, 22, 63, 87]
合計値:323.0
平均値:64.6
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?