조컴퓨터

200821 OOP 07 - Java Array, Math, Random 본문

자바 웹개발자 과정/JAVA

200821 OOP 07 - Java Array, Math, Random

챠오위 2020. 8. 27. 09:51

2차원 배열

→ [행][열]

 

앞서 공부한 배열은 값 목록으로 구성된 1차원 배열이다. 이와는 달리 값들이 행과 열로서 구성된 배열을 2차원 배열이라 한다. 2차원 배열은 수학의 행렬을 떠올리면 되는데, 가로 인덱스와 세로 인덱스를 사용한다.

 

위의 표를 배열로 나타내면 다음과 같다.

 

int [][] kor=new int[2][3];
kor[0][0]=10;
kor[0][1]=20;
kor[0][2]=30;
kor[1][0]=40;
kor[1][1]=50;
kor[1][2]=60;

 

kor배열의 행과 열의 갯수

 

//kor배열의 행의 갯수
System.out.println(kor.length);		//2
		
//kor[0]행의 열의 갯수
System.out.println(kor[0].length);	//3

//kor[1]행의 열의 갯수
System.out.println(kor[1].length);	//3

 

ArrayIndexOutOfBoundsException 발생

인덱스의 범위를 벗어나는 경우 나타나는 결과값이다.

1차원 배열과 마찬가지로 해당 오류가 발생할 수 있다.

 

System.out.println(kor[2].length); //에러

 

 

예제) 위의 배열을 for문을 이용하여 출력하시오.

 

int [][] kor=new int[2][3];
kor[0][0]=10;
kor[0][1]=20;
kor[0][2]=30;
kor[1][0]=40;
kor[1][1]=50;
kor[1][2]=60;

for(int r=0; r<=1; r++) {
	for(int c=0; c<=2; c++) {
		System.out.println(kor[r][c]);
	}//for end
}//for end

/*
	10
	20
	30
	40
	50
	60
*/

 

 

배열타입, 열거타입

 

int[][] kor= {//배열타입, 열거타입
		{10,20,30}	//[0][0] [0][1] [0][2]
		,{40,50,60}	//[1][0] [1][1] [1][2]
}; //2행3열
		
int row=kor.length;	//2->2행
for(int r=0; r<row; r++) {
	int col=kor[r].length;
	
	for(int c=0; c<col; c++) {
		System.out.println(kor[r][c]);
	}//for end
    
}//for end

/*
	10
	20
	30
	40
	50
	60
*/

 

 

이때, 2차원 배열에서 각 행의 열의 갯수는 달라도 된다.

 

int[][] kor= {//배열타입, 열거타입
		{10,20}			//[0][0] [0][1]
		,{30,40,50,60}	//[1][0] [1][1] [1][2] [1][3]
		,{70,80,90}		//[2][0] [2][1] [2][2]
}; //2행3열

int row=kor.length;
for(int r=0; r<row; r++) {
	int col=kor[r].length;
    
	for(int c=0; c<col; c++) {
    	System.out.println(kor[r][c]);
	}//for end
    
}//for end

/*
	10
	20
	30
	40
	50
	60
	70
	80
	90
*/

 

ArrayIndexOutOfBoundsException 발생

인덱스의 범위를 벗어나는 경우 나타나는 결과값이다.

 

System.out.println(kor[4][4]); //에러

 

위의 코드를 출력하면 다음과 같은 결과값이 나온다.

 

 

 

 

문제1) 대문자, 소문자의 갯수를 각각 구하고 대소문자를 서로 바꿔서 출력하시오.

 

/*
	출력결과
	대문자 2개
	소문자 5개
	sOLdESK					
*/

 

내 답안 

 

char[] ch= {'S', 'o', 'l', 'D', 'e', 's', 'k'};
int size=ch.length;

int row=ch.length;
int Acount=0, acount=0;
for(int r=0; r<row; r++) {

	if(ch[r]>='A' && ch[r]<='Z') {
		Acount=Acount+1;
	}else if(ch[r]>='a' && ch[r]<='z'){
		acount=acount+1;
	}//if end
    
}//for end
System.out.println("대문자"+Acount+"개");
System.out.println("소문자"+acount+"개");

		
int out=0;
for(int r=0; r<row; r++) {

	if(ch[r]>='A' && ch[r]<='Z') {
		out=ch[r]+32; //소문자
		System.out.print((char)out);
	}else if(ch[r]>='a' && ch[r]<='z'){
		out=ch[r]-32; //대문자
		System.out.print((char)out);
	}//if end
    
}//for end
System.out.println();

/*
	대문자2개
	소문자5개
	sOLdESK
*/

 

선생님 답안

 

int upper=0;
int lower=0;
		
for(int i=0; i<size; i++) {
	if(ch[i]>='A' && ch[i]<='Z') {
		upper++;
		System.out.print((char)(ch[i]+32));
	}else if(ch[i]>='a' && ch[i]<='z') {
		lower++;
		System.out.print((char)(ch[i]-32));
	}//if end
}//for end

System.out.println();
System.out.println("대문자"+upper+"개"); //2
System.out.println("소문자"+lower+"개"); //5

/*
	sOLdESK
	대문자2개
	소문자5개
*/

 

간단한 아스키 코드 활용

 

 

 

문제2) 모음의 갯수를 구하시오.

 

내 답안

 

char[] ch= {'S', 'o', 'l', 'D', 'e', 's', 'k'};
int size=ch.length;

int row=ch.length;
int count=0;
for(int r=0; r<row; r++) {
	if(ch[r]=='A' || ch[r]=='E' || ch[r]=='I' || ch[r]=='O' || ch[r]=='U') {
		count=count+1;
	}else if(ch[r]=='a' || ch[r]=='e' || ch[r]=='i' || ch[r]=='o' || ch[r]=='u'){
		count=count+1;
	}//if end
}//for end
System.out.println(count+"개"); //2개

 

이 코드는 if-else if문으로 만들었다. 또는 if 단일문으로 만들어지면서 전부 나열하는 방법이 있다.

 

 

선생님 답안

 

int mo=0;
for(int i=0; i<size; i++) {
	switch(ch[i]) {
	case 'A':
	case 'E':
	case 'I':
	case 'O':
	case 'U':
	case 'a':
	case 'e':
	case 'i':
	case 'o':
	case 'u': mo++;
	}//switch end
}//for end
System.out.println("모음"+mo+"개"); //모음2개

 

switch문으로 case 내부에 모음을 담은 구조

 

 

 

문제3) num배열요소 중 음수의 갯수를 구하시오.

 

int[] num= {7,8,-9,5,6};
int size=num.length; //5
        
int count=0;
for(int i=0; i<size; i++) {
	if(num[i]<0) {
		count=count+1;
	}//if end
}//for end
System.out.println("음수의 갯수:"+count+"개"); 

//음수의 갯수:1개

 

 

문제4) 최대값, 최소값을 각각 구하시오.

 

int[] num= {7,8,-9,5,6};
int size=num.length; //5
        
int max=num[0]; //최대값
int min=num[0]; //최소값
for(int i=0; i<size; i++) {
	if(num[i]>max) {
		max=num[i];
	}//if end
	if(num[i]<min) {
		min=num[i];
	}//if end
}//for end
System.out.println("최대값:"+max);
System.out.println("최소값:"+min);

/*
최대값:8
최소값:-9
*/
		

 

위의 코드는 다음과 같은 과정을 거친 후 출력된다.

 

/*
	if(max<num[0]) max=num[0]
	if(max<num[1]) max=num[1]
	if(max<num[2]) max=num[2]
	if(max<num[3]) max=num[3]
	if(max<num[4]) max=num[4]
*/

 

 

문제5) num[4]요소의 등수를 구하시오.

 

내 답안

 

int[] num= {7,8,-9,5,6};
int size=num.length;

int[] rank= {1,1,1,1,1};
for(int i=0; i<size; i++) {
	for(int j=0; j<size; j++) {
    
		if(num[i]>num[j]) { //rank[i]값이 크면 rank[j](등수)+1
			rank[j]++;
		}//if end
        
	}//for end
}//for end
System.out.println(num[4]+"의 등수:"+rank[4]+"등");

//6의 등수:3등

 

등수를 나열하는 개념으로 접근하였다.

 

 

선생님 답안

 

int r=1;
for(int i=0; i<size; i++) {
	if(num[4]<num[i]) {
		r++;
	}//if end
}//for end
System.out.println(num[4]+"의 등수 "+r+"등"); 

//6의 등수 3등	

 

if문에서 num[4]가 나머지 값들의 크기 차이만 비교

 

 

 

문제6) num배열요소 각각의 등수를 구하시오.

 

int[] num= {7,8,-9,5,6};
int size=num.length; //5

int[] rank= {1,1,1,1,1};
for(int i=0; i<size; i++) {
	for(int j=0; j<size; j++) {
		if(num[i]<num[j]) {
			rank[i]=rank[i]+1;
		}//if end
	}//for end	
}//for end
		
for(int k=0; k<size; k++) {
	System.out.println(num[k]+"의 등수:"+rank[k]+"등");
}//for end

/*
	7의 등수:2등
	8의 등수:1등
	-9의 등수:5등
	5의 등수:4등
	6의 등수:3등
*/	

 

 

문제7) 성적프로그램

 

String[] name= {"라일락", "진달래", "개나리", "무궁화", "장미"};
int[] kor= {100, 50, 95, 80, 60};
int[] eng= {100, 55, 95, 85, 40};
int[] mat= {100, 60, 35, 90, 30};

 

이 학생들의

1) 평균,

2) (평균을 기준으로 한) 등수,

3) 과락 (합격, 재시험, 불합격 여부를 포함),

4) 평균 10점당 * 한 개씩 출력

5) 평균 95점 이상이면 장학생

1) ~ 5) 각각을 출력하시오.

 

 

1) 평균 구하기

 

String[] name= {"라일락", "진달래", "개나리", "무궁화", "장미"};
int[] kor= {100, 50, 95, 80, 60};
int[] eng= {100, 55, 95, 85, 40};
int[] mat= {100, 60, 35, 90, 30};

int aver[]= {0, 0, 0, 0, 0};
int size=name.length;

for(int i=0; i<size; i++) {
	aver[i]=aver[i]+(kor[i]+eng[i]+mat[i])/3;	//**
}//for end

/*
	라일락의 평균:100점
	진달래의 평균:55점
	개나리의 평균:75점
	무궁화의 평균:85점
	장미의 평균:43점
*/

 

 

2) (평균을 기준으로 한) 등수 구하기

 

String[] name= {"라일락", "진달래", "개나리", "무궁화", "장미"};
int[] kor= {100, 50, 95, 80, 60};
int[] eng= {100, 55, 95, 85, 40};
int[] mat= {100, 60, 35, 90, 30};

int aver[]= {0, 0, 0, 0, 0};
int size=name.length;
for(int i=0; i<size; i++) {
	aver[i]=aver[i]+(kor[i]+eng[i]+mat[i])/3;
}//for end

int[] rank= {1,1,1,1,1};
for(int i=0; i<size; i++) {
	for(int j=0; j<size; j++) {
    
		if(aver[i]<aver[j]) {
			rank[i]=rank[i]+1;
		}//if end
        
	}//for end	
}//for end
		
for(int i=0; i<size; i++) {
	System.out.println(name[i]+"의 등수:"+rank[i]+"등");
}//for end

/*
	라일락의 등수:1등
	진달래의 등수:4등
	개나리의 등수:3등
	무궁화의 등수:2등
	장미의 등수:5등
*/

 

 

3) 과락 (합격, 재시험, 불합격 여부를 포함)

 

내 답안 (위의 코드 생략)

for(int i=0; i<size; i++) {
	System.out.print(name[i]+" ");
	System.out.print(kor[i]+" ");
	System.out.print(eng[i]+" ");
	System.out.print(mat[i]+" ");
	System.out.print(aver[i]+" ");
	System.out.print(rank[i]+" ");

	if(aver[i]>=70) {
    
		if(kor[i]>=40 && eng[i]>=40 && mat[i]>=40) {
			System.out.print("합격"+" ");		
		}else {
			System.out.print("재시험"+" ");
		}//if end
        
	}else {
		System.out.print("불합격"+" ");
	}//if end
    System.out.println(); //줄바꿈. 4)에서 삭제
    
}//for end

/*
	라일락 100 100 100 100 1 합격 
	진달래 50 55 60 55 4 불합격 
	개나리 95 95 35 75 3 재시험 
	무궁화 80 85 90 85 2 합격 
	장미 60 40 30 43 5 불합격 
*/

 

선생님 답안 (위의 코드 생략)

 

for(int i=0; i<size; i++) {
	System.out.print(name[i]+" ");
	System.out.print(kor[i]+" ");
	System.out.print(eng[i]+" ");
	System.out.print(mat[i]+" ");
	System.out.print(aver[i]+" ");
	System.out.print(rank[i]+" ");
    
    if(aver[i]>=70) {
		if(kor[i]<40 || eng[i]<40 || mat[i]<40) {
			System.out.print("재시험"+" ");
					
		}else {
			System.out.print("합격"+" ");
		}//if end
	}else {
		System.out.print("불합격"+" ");
	}//if end
	System.out.println(); //줄바꿈. 4)에서 삭제
    
}//for end

/*
	라일락 100 100 100 100 1 합격 
	진달래 50 55 60 55 4 불합격 
	개나리 95 95 35 75 3 재시험 
	무궁화 80 85 90 85 2 합격 
	장미 60 40 30 43 5 불합격 
*/

 

내 답안은 if문 and로 선생님 답안은 if문 or로

 

 

4) 평균 10점당 * 한 개씩 출력

 

내 답안 (위의 코드 생략)

 

for(int j=0; j<aver[i]/10; j++) {
	System.out.print("*");
}//for end
System.out.println(); //5)에서 삭제

/*
	라일락 100 100 100 100 1 합격 **********
	진달래 50 55 60 55 4 불합격 *****
	개나리 95 95 35 75 3 재시험 *******
	무궁화 80 85 90 85 2 합격 ********
	장미 60 40 30 43 5 불합격 ****
*/

 

선생님 답안 (위의 코드 생략)

 

for(int star=1; star<=aver[i]/10; star++) {
	System.out.print("*");
}//for end
System.out.println(); //5)에서 삭제

/*
	라일락 100 100 100 100 1 합격 **********
	진달래 50 55 60 55 4 불합격 *****
	개나리 95 95 35 75 3 재시험 *******
	무궁화 80 85 90 85 2 합격 ********
	장미 60 40 30 43 5 불합격 ****
*/

 

 

5) 평균 95점 이상이면 장학생

 

if(aver[i]>=95) {
	System.out.print(" "+"장학생");
}//if end
System.out.println(); //줄바꿈

/*
	라일락 100 100 100 100 1 합격 ********** 장학생
	진달래 50 55 60 55 4 불합격 *****
	개나리 95 95 35 75 3 재시험 *******
	무궁화 80 85 90 85 2 합격 ********
	장미 60 40 30 43 5 불합격 ****
*/

 

간단하게 풀이할 수 있다. 재밌다.

 

 

 

 

Math, Random 클래스

java.lang.Math 클래스는 수학 계산에 사용할 수 있는 메소드를 제공한다. Math 클래스가 제공하는 메소드는 모두 정적(static)이므로 Math 클래스로 바로 사용이 가능하다.

 

 

절대값

 

System.out.println(Math.abs(-3));	//3
System.out.println(Math.abs(2.4));	//2.4

 

소수점 올림

 

System.out.println(Math.ceil(1.3));	//2.0

 

소수점 버림

 

System.out.println(Math.floor(2.7));	//2.0

 

반올림

 

System.out.println(Math.round(3.8));	//4

 

최대값

 

System.out.println(Math.max(3, 5));	//5
System.out.println(Math.max(2, Math.max(4, 6))); //6

 

 

난수 : random값. 무작위로 발생한 값

난수 발생 범위 : 0.0<=r<1.0

 

System.out.println(Math.random());
System.out.println(Math.random()*2); //난수 발생 범위 2배
//0 1
System.out.println((int)(Math.random()*2)); //정수
//0 1 2 3
System.out.println((int)(Math.random()*4));
//0 1 2 3 4 5
System.out.println((int)(Math.random()*6));
//0 ~ 44
System.out.println((int)(Math.random()*45));

 

 

예제1) 주사위 수의 범위 1 ~ 6 발생

 

System.out.println((int)(Math.random()*6)+1);

 

 

예제2) 로또 번호 범위 1 ~ 45 발생

 

System.out.println((int)(Math.random()*45)+1);
System.out.println((int)(Math.random()*45)+1);
System.out.println((int)(Math.random()*45)+1);
System.out.println((int)(Math.random()*45)+1);
System.out.println((int)(Math.random()*45)+1);
System.out.println((int)(Math.random()*45)+1);

 

 

 

문제) 로또 번호

        1 ~ 45 중에서 서로 겹치지 않게 6개 발생

 

내 답안

 

int[] lotto=new int[6];
int str=lotto.length;
		
for(int i=0; i<str; i++) {
	lotto[i]=(int)(Math.random()*45)+1;
			
	for(int j=0; j<i; j++) {
		lotto[j]=(int)(Math.random()*45)+1;

		if(lotto[i]!=lotto[j]) {
			break;
		}//if end
				
	}//for end
}//for end

Arrays.sort(lotto); //내림차순 정렬하기
				
for(int a=0; a<6; a++) {
	System.out.println(lotto[a]);
}//for end

 

1) new연산자로 lotto배열이 들어갈 장소 6개를 만들어 주고,

2) 모든 계산 과정 이전에 lotto[0]을 먼저 구함

3) 그 다음 lotto[1]을 구하면

4) lotto[0]과 lotto[1]을 비교할 수 있도록 값이 만들어지므로 if문에서 둘을 비교

5) 이때 두 값이 같지 않으면 break 사용

6) 앞서 구한 lotto[0], lotto[1]이 배열값에 투입

7) 앞의 과정을 반복하여 다음 배열값도 구함

 

 

선생님 답안

 

int[] lotto=new int[6];
int str=lotto.length;

for(int a=0; a<6; a=a+1) {
	lotto[a]=(int)(Math.random()*45)+1;
		
    for(int b=0; b<a; b=b+1) {
    
		if(lotto[a]==lotto[b]) {
			a--;	//빠꾸
			break;	//다시 받아라 ex)a=3 상태로 탈출 다시 a=3+1~~
		}//if end
        
	}//for end
}//for end

Arrays.sort(lotto); //배열하기
				
for(int a=0; a<6; a++) {
	System.out.println(lotto[a]);
}//for end

 

 

 

과제1) 각 행의 모음의 갯수를 구하시오.

 

내 답안 

 

char[][] ch= {
		{'R', 'e', 'd'}
		,{'G', 'r', 'e', 'e', 'n'}
		,{'B', 'l', 'u', 'e'}
		,{'O', 'r', 'a', 'n', 'g', 'e'}
};

int count=0;
for(int i=0; i<ch.length; i++) {
	for(int j=0; j<ch[i].length; j++) {
				
		if(ch[i][j]=='A' || ch[i][j]=='E' || ch[i][j]=='I'
        					  || ch[i][j]=='O' || ch[i][j]=='U') {
			count++;
		}else if(ch[i][j]=='a' || ch[i][j]=='e' || ch[i][j]=='i'
        					  || ch[i][j]=='o' || ch[i][j]=='u') {
			count++;
		}//if end
				
	}//for end
}//for end
System.out.println("모음의 갯수:"+count+"개");

//모음의 갯수:8개

 

for문 중첩으로 배열문의 범위를 지정하고

if문으로 모음의 범위를 지정한 후

count로 모음이 나오는 횟수를 계산하여 출력한다.

 

 

 

과제2) 대각선 방향의 각 요소의 합을 구하시오.

         대각선 ↘ 방향의 합 : 3+5+9=17

         대각선 ↙ 방향의 합 : 1+5+7=13

 

내 답안

 

int[][] num= {
		{3, 2, 1}
		,{4, 5, 6}
		,{7, 8, 9}
};

int rsum=0, lsum=0;
for(int i=0; i<num.length; i++) {
	for(int j=0; j<num[i].length; j++) {
		if(i==j) { //[0][0], [1][1], [2][2]
			rsum=rsum+num[i][j];
		}//if end
				
		if(i+j==2) { //[0][2], [1][1], [2][0]
			lsum=lsum+num[i][j];
		}//if end
	}//for end
}//for end
System.out.println("대각선 ↘ 방향의 합:"+rsum);
System.out.println("대각선 ↙ 방향의 합:"+lsum);

/*
	대각선 ↘ 방향의 합:17
	대각선 ↙ 방향의 합:13
*/

 

rsum과 lsum은 단순히 대각성 방향에 따른 합의 값을 분류하기 위해 나눈 것이고 

if 단일문을 두 번 사용하여 각 방향에 따른 합의 값을 구한다. 

간단하게 도출된다.