JAVA/기본 이론

JAVA | 배열(Array)(1)

로아다 2023. 3. 13. 23:45
728x90
반응형
배열(Array)

- 같은 타입 변수를 여러개 선언하고 싶을 때 사용하는 문법

- 배열을 선언 할 때 선언과 동시에 배열의 크기를 정해야 한다.

- 배열을 선언한 후 각 변수를 방 번호(index)로 구분한다.

- 배열의 인덱스는 0 ~ 길이 -1번 까지 있다. (문자열과 유사함)

- 배열은 변수와는 다르게 처음 선언할 때 모든 방의 값을 초기화 해준다.

  (정수 : 0, 실수 : 0, boolean : false, 참조형 : null)

 

배열 선언 방식

1. 타입[ ] 변수명 = new 타입[크기];

2. 타입[ ] 변수명 = { v1, v2, v3, v4, ... };

3. 타입[ ] 변수명 = new 타입[] { v1, v2, v3, v4, ... };

 


  • char타입 배열(문자열)
public class B13_Array {
	public static void main(String[] args) {
    	char[] text = new char[15]; // 문자 배열 (문자열)
		
		text[0] = 'h';
		text[1] = 'e';
		text[2] = 'l';
		text[3] = 'l';
		text[4] = 'o';
		text[5] = 0;
		
		System.out.println(text);
    }
}

 


 

  • int타입 배열
public class B13_Array {
	public static void main(String[] args) {
	// int타입 변수를 1000개 선언하기
		// 배열 크기가 1000일 때 인덱스는 0 ~ 999까지 존재한다.
		int[] a = new int[1000];
		
		
		// ※ 초기화 하지 않은 변수는 사용할 수 없다.
		int num;
//		System.out.println(num);
		
		
		// 배열에 값 넣기
		a[0] = 5;
		a[1] = 10;
		a[2] = 99;
		
		// 배열에 들어있는 값 꺼내 쓰기
		System.out.println(a[0]);
		System.out.println(a[1]);
		System.out.println(a[555]); // 값을 넣은 적 없는 배열에는 0이 들어있다.
    }
}

 


 

  • 참조형 타입 배열
public class B13_Array {
	public static void main(String[] args) {
	String[] words = 
			{"apple", "banana", "kiwi", "mango", "grape", "melon"};
		
		System.out.println(words[0]);
		System.out.println(words[1]);
		System.out.println(words[2]);
    }
}

 


배열의 반복문
public class B13_Array {
	public static void main(String[] args) {
		// 배열은 반복문과 함께 사용하기 아주 좋은 형태로 되어있다.
		for (int i = 0; i < words.length; ++i) {
			System.out.println(words[i]);
		}
    }
}

 


각 타입의 초기값
public class B13_Array {
	public static void main(String[] args) {
		// boolean의 초기값 : false
		boolean[] passExam = new boolean[30];
		System.out.println(passExam[7]);
		
		// 참조형의 초기값 : null
		String[] snacks = new String[10];
		System.out.println(snacks[5]);
		
		String[] animals = new String[] {"cat", "dog", "lion"};
		System.out.println(animals[2]);
		}
    }
}

 

 


 

 

 

Quiz

 1. 100개의 점수(0 ~ 100)를 랜덤으로 생성하여 배열에 저장

 2. 배열에 저장된 값을 한 줄에 10개씩 출력 (60점 미만인 점수는 X로 표시)

 3. 모든 점수의 평균을 출력 (소수 둘째자리까지 출력)

 4. 가장 높은 점수와 가장 낮은 점수를 출력

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Answer
package quiz;

public class B13_RandomScore {
	/*
		1. 100개의 점수(0점 ~ 100점)를 랜덤으로 생성하여 배열에 저장

		2. 배열에 저장된 값을 한 줄에 10개씩 출력
			(60점 미만인 점수는 X로 표시)

	 	3. 모든 점수의 평균을 출력 (소수 둘째자리까지 출력)

	 	4. 가장 높은 점수와 가장 낮은 점수를 출력
	 */

	public static void main(String[] args) {

		int[] score = new int[100];
		int count = 0;
		int total = 0;
		double average = 0;
		int max = 0;
		int min = 0;

		for (int i = 0; i < score.length; ++i) {
			// 1. 100개의 점수(0점 ~ 100점)를 랜덤으로 생성하여 배열에 저장
			score[i] = (int)(Math.random() * 101);

			++count;

			// 2. 배열에 저장된 값을 한 줄에 10개씩 출력
			if (score[i] < 60) {
				System.out.printf("%d(%c)\t", score[i], 'X');
			} else {
				System.out.printf("%d\t", score[i]);
			}

			if (count == 10) {
				System.out.println();
				count = 0;
			}

			total += score[i];

			// 4. 가장 높은 점수와 가장 낮은 점수를 출력
			min = score[0];
			for (int j = 0; j < score.length; ++j) {
				max = max > score[j] ? max : score[j];
				min = min < score[j] ? min : score[j];
			}
		}
		
		// 3. 모든 점수의 평균을 출력 (소수 둘째자리까지 출력)
		average = total / 100.0;
		System.out.printf("평균: %.2f\n", average);
		
		System.out.println("최고점: " + max);
		System.out.println("최하점: " + min);
	}
}
728x90
반응형