Java 참조 타입 #4

jjinny_0609·2023년 2월 8일
0

Java

목록 보기
9/31

5-2 배열 확인 문제

public class Exercise04 {
	public static void main(String[] args) {
		int max = 0;
		int[] arr = {1, 5, 3, 8, 2};
		
		// max변수에 저장되어 있는 값보다 배열에 저장되어 있는 값이 크면 
		for(int i=0; i< arr.length; i++) {
			if(max<arr[i]) {
				// 배열에 있는 값을 max 변수에 저장
				max = arr[i];
			}
		}
		System.out.println("max : " + max);
	}
}



package ch05;

public class Exercise05 {
	public static void main(String[] args) {
		int[][] array = {
				{95, 86},
				{83, 92, 96},
				{78, 83, 93, 87, 88}
		};
		
		int sum = 0;
		double avg = 0.0;
		int count = 0;//몇개가 배열로 들어갔는지 카운트해서 저장하기 위함
		
		for(int i = 0; i<array.length; i++) {
			for(int j=0; j<array[i].length; j++) {
				//합계
				sum += array[i][j];
				count++;	//배열에 들어갈때 마다 카운트수를 올려줌
			}
		}
		//평균 = 합계 / array전체 건수
		
		avg = (double)sum / count;
		
		System.out.println("sum : " + sum);
		System.out.println("avg : " + avg);
	}
}



6번 문제

import java.util.Scanner;

public class Exercise06 {
	public static void main(String[] args) {
		boolean run = true;	// true를 통해 계속 실행시키기 위해서 들어가는 값
		int studentNum = 0;	// 학생수(키보드로 입력을 할 수 있게 처리)
		int[] scores = null;// 각 학생의 점수
		Scanner scanner = new Scanner(System.in);
		
		while(run) {
			System.out.println("----------------------------------------------");
			System.out.println("1.학생수 | 2. 점수입력 | 3. 점수리스트 | 4. 분석 | 5. 종료");
			System.out.println("----------------------------------------------");
			System.out.print("선택> ");
			
			int selectNo = Integer.parseInt(scanner.nextLine());
			
			if(selectNo==1) {
				// 배열로 값을 넣어야함
				System.out.print("학생수> ");
				studentNum = Integer.parseInt(scanner.nextLine());
				scores = new int[studentNum];
				//배열은 참조타입이라 주소가 없음	new int[studentNum]를 만나서 주소를 새로 생성
			}else if(selectNo==2) {
				for(int i=0; i<scores.length; i++) {
					System.out.print("scores["+i+"]> ");
					scores[i] = Integer.parseInt(scanner.nextLine());
				}
			}else if(selectNo==3) {
				for(int i=0; i<scores.length; i++) {
					System.out.println("scores["+i+"]>"+scores[i]);
				}
			}else if(selectNo==4) {
				int max = 0;	//최고 점수를 저장하기 위한 변수
				int sum = 0;	//합계를 저장하기 위한 변수
				double avg = 0;	//평균 점수를 저장하기 위한 변수(소수점 때문에 double을 사용)
				for(int i=0; i < scores.length; i++) {
					// 최고점수
					if(max<scores[i]) {
						max = scores[i];
					}
					// 평균점수
					sum += scores[i];	// sum = sum + scores[i];
					avg = (double)sum / studentNum;	//소수점 계산을 위해서 타입 하나를 더블로 변경
				}
				System.out.println("최고 점수 :" + max);
				System.out.println("평균 점수 :" + avg);
			}else if(selectNo==5) {
				run = false;
			}
		}
		System.out.println("프로그램 종료");
	}
}


profile
뉴비 개발자 입니다. velog 주소 : https://velog.io/@jjinny_0609 Github 주소 :

0개의 댓글