명품 JAVA 프로그래밍

명품 JAVA 프로그래밍 7장 실습문제 4

anycoding 2021. 12. 1. 20:08
반응형

문제

다음 프로그램은 ArrayList에 20개의 임의의 실수를 삽입하고 모든 실수를 출력하는 프로그램이다. 모든 실수를 출력하는 부분을 Iterator를 이용하여 수정하라

 

문제 소스

import java.util.ArrayList;
public class Main4 {
	public static void main(String[] args) {
		ArrayList<Double> a = new ArrayList<Double>();
		for(int i = 0;i<20;i++) {
			double d = Math.random()*100; // 0.0 ~ 100.0 사이의 랜덤한 실수
			a.add(d);
		}
		// 이 부분 수정
		for(int i = 0;i<20;i++)
		{
			System.out.println(a.get(i));
		}

	}

}

 

소스 코드

(사용할 클래스가 포함된 패키지 선언 방법이 모를 땐, Ctrl + Shift + o(알파벳) 누르시면 자동으로 추가해줍니다.)

import java.util.ArrayList;
import java.util.Iterator;
public class Main4 {
	public static void main(String[] args) {
		ArrayList<Double> a = new ArrayList<Double>();
		for(int i = 0;i<20;i++) {
			double d = Math.random()*100; // 0.0 ~ 100.0 사이의 랜덤한 실수
			a.add(d);
		}
		// 이 부분 수정
		Iterator<Double> it = a.iterator(); 
		// double이 아닌 Double사용해야함 기본 타입 사용 불가
		while(it.hasNext()) { // 값이 있을때 까지 실행
			double n = it.next(); // 다음 값 n에 저장
			System.out.println(n); // 출력
		}

	}

}

결과

21.682354414100423
68.12176249839573
90.18336487034124
20.390411829434807
46.864036416920825
23.31759658352963
28.144614681214698
30.33753351616787
37.83634698945536
14.969898519803415
25.001090784183265
26.670294132217432
21.390460546060865
35.468423285316895
82.38578035008013
65.66836688688392
12.958212033635984
17.656082212719248
83.61235339930406
55.07903459309939

출력결과는 컴파일 할 때마다 달라요.

반응형