middlemoon
Day03. 배열 본문
package chap3;
public class ArrayTest {
public static void main(String[] args) {
int scores [] = new int[10];
System.out.println("학생수=" + scores.length);
//scores 배열 값 출력 "반복" 출력
for(int index = 0; index < 10; index++) {
System.out.println(scores[index]);
}
for(int index = 0; index < 10; index++) {
scores[index] = (int)(Math.random() * 100) + 1;
System.out.println(scores[index]);
}
//총점 , 평균
int sum = 0;
int avg = 0;
for(int index = 0; index < scores.length; index++) {
sum += scores[index]; //총점
}
avg = sum / scores.length; //평균
System.out.println("총점= " + sum + ", 평균= " + avg);
//1등
int max = 0;
//84 16 57 9.....
for(int index = 0; index < scores.length; index++) {
//index = 0 scores[index] = 84 max = 0
//index = 1 scores[index] = 16 max = 84
//index = 2 scroes[index] = 57 max = 84
//.....
if(scores[index] > max) {
max = scores[index];
}
}
System.out.println("1등=" + max);
//최소값 꼴등
int min = 999;
//84 16 57 9.....
for(int index = 0; index < scores.length; index++) {
//index = 0 scores[index] = 84 max = 0
//index = 1 scores[index] = 16 max = 84
//index = 2 scores[index] = 57 max = 84
//.....
if(scores[index] < min) {
max = scores[index];
}
}
System.out.println("마지막 등=" + max);
}
//1등
}
코드리뷰 : 학생 수 일정 기준[10] 배열안에 넣고, length의 길이만큼 출력을 해준다.
총점만을 구해주는 sum += scores[index], 평균을 구해주는 avg=sum / scores.length 을 각각선언 후 마지막에 총점과 평균의 결과값을 나오게 도출해주었다. for 문과 if문을 이용해 1등과 마지막 등을 구할수있도록 변수값에 선언해주었다.
핵심은 반복문과 if문을 적절히 사용해 , 원리를 이해하는것에 초점을 맞추었다. 배열의 기본형식이다.
'Develop > JAVA' 카테고리의 다른 글
JAVA 객체지향 프로그래밍 I (0) | 2023.01.12 |
---|---|
Day05.HashMap (0) | 2022.08.15 |
Day04.함수 (0) | 2022.07.19 |
Day02.변수 (0) | 2022.07.10 |
Day01. 자동형변환 (0) | 2022.07.08 |