본문 바로가기

Java 웹 개발

21.08.24 - 웹 개발 입문 10일차

 

배열-개요

변수 : 단일 데이터 저장소
배열 : 다중 데이터 저장소

- 배열은 변수만으로 처리하기 어려워서 나온 개념
- 어떤 상황에서 변수로 처리하는 것이 어려운지 파악하는 것이 중요!

 

 

ex. 10, 20, 30, 40, 50 이라는 숫자를 저장 및 합계계산 후 출력

 

1. 변수로 표현

package array;

public class Test01 {

	public static void main(String[] args) {
		//10, 20, 30, 40, 50 이라는 숫자를 저장 및 합계계산 후 출력
		int a, b, c, d, e;

		a = 10;
		b = 20;
		c = 30;
		d = 40;
		e = 50;

		int total = a + b + c + d + e;

		System.out.println("a = " + a);
		System.out.println("b = " + b);
		System.out.println("c = " + c);
		System.out.println("d = " + d);
		System.out.println("e = " + e);

		System.out.println("total = " + total);
	}
}

 

 

 

2. 배열로 표현하기

package array;

public class Test02 {

	public static void main(String[] args) {
		
		//10, 20, 30, 40, 50 이라는 숫자를 저장 및 합계계산 후 출력
		int[] arr = new int[5];//(arr) -----> [ 0 ][ 0 ][ 0 ][ 0 ] [ 0 ]
		
		arr[0] = 10;
		arr[1] = 20;
		arr[2] = 30;
		arr[3] = 40;
		arr[4] = 50;

		int total = arr[0] + arr[1] + arr[2] + arr[3] + arr[4];
		
		System.out.println("arr[0] = " + arr[0]);
		System.out.println("arr[1] = " + arr[1]);
		System.out.println("arr[2] = " + arr[2]);
		System.out.println("arr[3] = " + arr[3]);
		System.out.println("arr[4] = " + arr[4]);
		
		System.out.println("total = " + total);
		
	}

}

 

3. 배열 정리하기

package array;

public class Test03 {

	public static void main(String[] args) {

		// 10, 20, 30, 40, 50 이라는 숫자를 저장 및 합계계산 후 출력
		int[] arr = new int[5];// (arr) ------> [ 0 ] [ 0 ] [ 0 ] [ 0 ] [ 0 ]

		// arr = 10;//말이 안되는 코드
		int value = 10;
		for (int i = 0; i < 5; i++) {
			arr[i] = value;
			value += 10;
		}

		// int total = arr[0] + arr[1] + arr[2] + arr[3] + arr[4];
		int total = 0;
		for (int i = 0; i < 5; i++) {
			total += arr[i];
		}

		for (int i = 0; i < 5; i++) {
			System.out.println("arr[" + i + "] = " + arr[i]);
		}

		System.out.println("total = " + total);
	}
}

- 정답

arr[0] = 10
arr[1] = 20
arr[2] = 30
arr[3] = 40
arr[4] = 50
total = 150

 

 

 

Q. 사용자에게 3개의 숫자를 배열에 입력받아 합계를 계산한 뒤 출력

package array;

import java.util.Scanner;

public class Test04 {

	public static void main(String[] args) {

		int[] arr = new int[3];
		Scanner sc = new Scanner(System.in);
		System.out.println("숫자를 3개 입력");
		for (int i = 0; i < 3; i++) {
			arr[i] = sc.nextInt();
		}
		sc.close();

		int total = 0;
		for (int i = 0; i < 3; i++) {
			total += arr[i];
		}

		for (int i = 0; i < 3; i++) {
			System.out.println("점수 = " + arr[i]);
		}
		System.out.println("total = " + total);

	}
}

- 정답

숫자를 3개 입력
90
40
56
점수 = 90
점수 = 40
점수 = 56
total = 186

 

 

 

 

Q. 사용자에게 5명의 이름을 입력받아 출력

package array;

import java.util.Scanner;

public class Test05 {

	public static void main(String[] args) {

		String[] name = new String[5]; // 이름

		Scanner sc = new Scanner(System.in);

		System.out.println("이름을 5번 입력하세요");

		for (int i = 0; i < 5; i++) {
			name[i] = sc.nextLine();
		}
		sc.close();

		for (int i = 0; i < 5; i++) {
			System.out.println(name[i]);
		}

	}
}

- 정답

이름을 5번 입력하세요
가나다
라마바
사아자
차카타
파하
가나다
라마바
사아자
차카타
파하

 

 

 

다양한 종류의 배열 표현 방법 알아보기
- int, long, float, double, String

package array;

public class Test06 {

	public static void main(String[] args) {

		int[] a = new int[3];  //(a) -----> [ 0 ] [ 0 ] [ 0 ] 
		long[] b = new long[3];  //(b) -----> [ 0L ] [ 0L ] [ 0L ] 
		float[] c = new float[3];  //(c) -----> [ 0.0f ] [ 0.0f ] [ 0.0f ] 
		double[] d = new double[3];  //(d) -----> [ 0.0 ] [ 0.0 ] [ 0.0 ] 
		String[] e = new String[3];  //(e) -----> [ null ] [ null ] [ null ] 
		boolean[] f = new boolean[3];  //(f) -----> [ false ] [ false ] [ false ]
	}
}

 

 

 

배열의 생성 방법과 유용한 보조 기능

ex. 10, 20, 30을 배열에 저장

package array;

public class Test07 {

	public static void main(String[] args) {

		// 1) 칸 수를 지정하여 생성
		//int size = 3;
		//int[] a = new int[size];
		int[] a = new int[3];

		a[0] = 10;
		a[1] = 20;
		a[2] = 30;

		//for (int i = 0; i < size; i++) {
		for (int i = 0; i < a.length; i++) {
			System.out.println("a = " + a[i]);
		}

		// 2) 생성과 동시에 데이터 초기화
		// = 데이터 개수를 작성하면 Error!
		int[] b = new int[] { 10, 20, 30 };//(b) -----> [ 10 ] [ 20 ] [ 30 ]
		System.out.println("length = " + b.length);//배열 생성 시 배열의 크기를 저장하기 위한 장소

		for(int i = 0 ; i < b.length ; i ++) {
			System.out.println("b = " + b[i]);
		}
	}
}

- 정답

a = 10
a = 20
a = 30
length = 3
b = 10
b = 20
b = 30

 

 

 

Q. 우리반 학생 10명의 시험점수는 다음과 같습니다.
95점, 82점, 77점, 69점, 75점, 62점, 76점, 77점, 85점, 93점
우리반 학생들의 점수를 배열에 저장하고 출력
우리반 학생 중 80점 이상을 획등한 학생들의 숫자를 구하여 출력
우리반 평균을 구하여 출력
만약 전학생의 점수가 76점이라면 전학생의 등수는 몇등인지 계산하여 출력(사용자 입력도 가능)

package array;

public class Test08 {

	public static void main(String[] args) {

		// 입력(준비)
		// int[] score = new int[10];
		int[] score = new int[] { 95, 82, 77, 69, 75, 62, 76, 77, 85, 93 };

		// 1. 전체 점수를 출력
		for (int i = 0; i < score.length; i++) {
			System.out.println("점수 = " + score[i]);
		}

		// 2. 80점 이상을 획득한 인원 수 출력(카운트)
		for (int i = 0; i < score.length; i++) {
			if (score[i] >= 80) {
				System.out.println("80점 이상인 학생 = " + score[i]);
			}
		}

		// 3. 우리반 평균 출력
		// 평균 = 총점 / 인원수 = 총점 / score.length

		int total = 0;
		for (int i = 0; i < score.length; i++) {
			total += score[i];
		}

		float average = (float) total / score.length;
		System.out.println("평균 = " + average);

		// 4. 전학생의 예상 등수 구하기
		int newScore = 76;
		int rank = 1;

		for (int i = 0; i < score.length; i++) {
			if (newScore < score[i]) {// 나보다 잘난놈을 발견했다면
				rank++;
			}
		}

		System.out.println("전학생 등수 = " + rank);

	}
}

- 정답

점수 = 95
점수 = 82
점수 = 77
점수 = 69
점수 = 75
점수 = 62
점수 = 76
점수 = 77
점수 = 85
점수 = 93
80점 이상인 학생 = 95
80점 이상인 학생 = 82
80점 이상인 학생 = 85
80점 이상인 학생 = 93
평균 = 79.1
전학생 등수 = 7

 

Q. 위에 추가문제 : ranking 배열에 "모든 학생의 순위" 점수 순서대로 계산하여 저장 후 점수와 연결하여 출력

// ex : ranking[0]에는 score[0] 학생의 순위를 구하여 저장

package array;

public class Test8_1 {

	public static void main(String[] args) {

		int[] score = new int[] { 95, 82, 77, 69, 75, 62, 76, 77, 85, 93 };
		int[] ranking = new int[score.length];// score 길이만큼 ranking 생성

		// ranking[k] 에 들어갈 순위를 계산
		for (int k = 0; k < score.length; k++) {
			ranking[k] = 1;
			for (int i = 0; i < score.length; i++) {
				if (score[k] < score[i]) {
					ranking[k]++;
				}
			}
		}

		for (int i = 0; i < score.length; i++) {
			System.out.println("점수 = " + score[i] + ", 등수 = " + ranking[i] + "등");
		}
	}
}

- 정답

점수 = 95점, 등수 = 1등
점수 = 82점, 등수 = 4등
점수 = 77점, 등수 = 5등
점수 = 69점, 등수 = 9등
점수 = 75점, 등수 = 8등
점수 = 62점, 등수 = 10등
점수 = 76점, 등수 = 7등
점수 = 77점, 등수 = 5등
점수 = 85점, 등수 = 3등
점수 = 93점, 등수 = 2등

 

 

 

 

Q. 우리반 학생 10명의 시험점수는 다음과 같습니다.
95점, 82점, 77점, 69점, 75점, 62점, 76점, 77점, 85점, 93점
우리반에서 가장 높은 점수를 구하여 출력
우리반에서 가장 낮은 점수를 구하여 출력

package array;

public class Test09 {

	public static void main(String[] args) {

		// 입력(준비)
		int[] score = new int[] { 95, 82, 77, 69, 75, 62, 76, 77, 85, 93 };

		// 1 최대값 찾기
		// (1)맨 앞에 있는 점수가 가장 큰 점수일 것이라고 가정을 하고 시작
		// (2) 그 뒤에 있는 데이터들과 비교하여 더 큰 데이터가 나오면 갱신
		// (3) 모든 과정이 종료된 뒤 남은 데이터가 최대값

		// (1)
		int max = score[0];

		// (2)
		// 최대 구하기
		for (int i = 1; i < score.length; i++) {
			if (max < score[i]) { // max 보다 더 큰 데이터가 score에 존재한다면
				max = score[i]; // max 를 현재의 점수( score[i]로 변경(갱신)한다.
			}
		}

		// (3)
		// 최대 출력
		System.out.println("최고 점수 = " + max + "점");

		// 최소 초기 세팅
		int min = score[0];

		// 최소 구하기
		for (int i = 1; i < score.length; i++) {
			if (min > score[i]) {
				min = score[i];
			}
		}
		// 최소 출력
		System.out.println("최저 점수 = " + min + "점");

	}
}

- 정답

최고 점수 = 95점
최저 점수 = 62점

 

 

 

Q. 우리반 학생 10명의 시험점수는 다음과 같습니다.
95점, 82점, 77점, 69점, 75점, 62점, 76점, 77점, 85점, 93점
우리반에서 가장 높은 점수인 학생의 데이터 위치를 구하여 출력
우리반에서 가장 낮은 점수인 학생의 데이터 위치를 구하여 출력

package array;

public class Test10 {

	public static void main(String[] args) {

		int[] score = new int[] { 95, 82, 77, 69, 75, 62, 76, 77, 85, 93 };

		// 찾아야 하는 정보는 값이 아니라 위치(index)
		// 맨 앞 위치가 가장 큰 점수가 있는 위치일 것이라고 가정을 하고 시작
		// 그 뒤에 있는 데이터들과 비교하여 더 큰 데이터가 나오면 위치 갱신
		// 모든 과정이 종료된 뒤 남은 데이터가 최대값의 위치

		int maxIndex = 0;

		for (int i = 1; i < score.length; i++) {
			if (score[maxIndex] < score[i]) {
				maxIndex = i;
			}
		}

		System.out.println("최대값 위치 = " + maxIndex);
		// 배열의 특성상 위치를 알면 데이터도 알 수 있다.
		System.out.println("최대값 = " + score[maxIndex]);

		int minIndex = 0;
		for (int i = 1; i < score.length; i++) {
			if (score[minIndex] > score[i]) {
				minIndex = i;
			}
		}

		System.out.println("최대값 위치 = " + minIndex);
		// 배열의 특성상 위치를 알면 데이터도 알 수 있다.
		System.out.println("최대값 = " + score[minIndex]);

	}
}

- 정답

최대값 위치 = 0
최대값 = 95
최대값 위치 = 5
최대값 = 62

 

 

배열 위치 변경

배열의 위치를 이용하여 할 수 있는 작업
배열에서는 위치를 이용하여 데이터들을 서로 바꾸거나 이동할 수 있다

(주의) 자바에서는 변수간의 맞교환이 불가능하다(참고로 파이썬에선 가능)
추가적인 공간을 하나 더 만들어서 우회적으로 교환

 

 

 

Q. 1번, 4번 위치 변경해보기

package array;

public class Test11 {

	public static void main(String[] args) {

		//입력
		int[] data = new int[] {30, 50, 20, 10, 40};
		System.out.println(data.length);
		
		//처리
		int temp = data[1];
		data[1] = data[4];
		data[4] = temp;
 		
		//출력
		for(int i=0; i <data.length; i++) {
			System.out.println(data[i]);
		}
	}
}

- 정답

30 50 20 10 40

30 40 20 10 50

 

 

 

10일차 과제

① 다음과 같은 데이터를 배열에 저장한 뒤 요구사항에 맞게 코드를 구현하세요
데이터 : 30, 50, 20, 10, 40
1. 배열을 순서대로 출력
2. 배열의 모든 데이터 위치를 반대로 변경하여 출력

package array;

public class Test13 {

	public static void main(String[] args) {

		int[] data = new int[] { 30, 50, 20, 10, 40 };
		for (int i = 0; i < data.length; i++) {
			System.out.print(data[i]);
			System.out.print(" ");
		}

		System.out.println("");

		for (int i = 0; i < data.length / 2; i++) {
			int temp = data[i];
			data[i] = data[data.length - 1 - i];
			data[data.length - 1 - i] = temp;
		}

		for (int i = 0; i < data.length; i++) {
			System.out.print(data[i]);
			System.out.print(" ");
		}
	}
}

- 정답

1. 30 50 20 10 40 
2. 40 10 20 50 30 

 

 

② 다음과 같은 데이터를 배열에 저장한 뒤 요구사항에 맞게 코드를 구현하세요
데이터 : 30, 50, 20, 10, 40
1. 배열 전체를 시계 방향으로 1번 회전
2. 배열 전체를 사용자가 입력한 칸만큼 시계 방향으로 회전

package array;

import java.util.Scanner;

public class Test14 {

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);
		System.out.print("회전 수를 입력하세요 : ");
		int rotate = sc.nextInt();
		sc.close();

		int[] data = new int[] { 30, 50, 20, 10, 40 };
		for (int i = 0; i < data.length; i++) {
			System.out.print(data[i]);
			System.out.print(" ");
		}

		System.out.println("");

		for (int n = 0; n < rotate; n++) {
			int temp = data[data.length - 1];
			for (int i = data.length - 1; i >= 1; i--) {
				data[i] = data[i - 1];
			}
			data[0] = temp;
		}
		for (int i = 0; i < data.length; i++) {
			System.out.print(data[i]);
			System.out.print(" ");
		}
	}
}

- 정답

회전 수를 입력하세요 : 2
30 50 20 10 40 
10 40 30 50 20