[Workshop04-문제7][Java] 배열 랜덤값의 최댓값 구하기 (Random 클래스)

박현아·2024년 3월 25일
0

문제

Scanner 클래스를 사용하여 입력 받은 사람 수 만큼 랜덤하게 키(height)값을 구하여 실행결과와 같이 출력하도록 구현하시오. (Random 클래스 사용)

자바 코드

Scanner sc = new Scanner(System.in);
		
System.out.println("키의 최댓값을 구합니다");
System.out.print("사람 수 :");
int num = sc.nextInt();
		
Random r = new Random();
		
int[] heights = new int[num];
		
for (int i=0; i<num; i++) {
	heights[i] = 100 + r.nextInt(100); // 100~199 중 난수 생성
	System.out.println("사람 " + (i+1) + ": " +heights[i]);
}
		
int max = heights[0];
		
for(int i=1;i<heights.length;i++) {
	if(heights[i]> max) {
	max = heights[i];
	}
}
		
System.out.println("최댓값은 " + max + "입니다.");

출력 값

키의 최댓값을 구합니다
사람 수 :5
사람 1: 117
사람 2: 110
사람 3: 182
사람 4: 140
사람 5: 150
최댓값은 182입니다.

참고

int java.util.Random.nextInt(int bound)

Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence. The general contract of nextInt is that one int value in the specified range is pseudorandomly generated and returned. All bound possible int values are produced with (approximately) equal probability. The method nextInt(int bound) is implemented by class Random.

Random 클래스는 0에서 지정한 값 전까지의 값 중 난수를 생성하여 출력한다.

0개의 댓글