5-1 다음은 배열을 선언하거나 초기화한 것이다. 잘못된 것을 고르고 그 이유를 설명하시오.
a. int [] arr [];
b. int[] arr = {1,2,3,};
c. int[] arr = new int [5];
d. int[] arr = new int [5]{1,2,3,4,5};
e. int arr[5];
f. int[] arr [] = new int [3][];

 

d :  두 번째 대괄호에 숫자를 넣지 말거나 초기화를 하면 안 된다.

e : 배열을 선언할 때 배열의 크기를 지정할 수 없다.



5-2 다음과 같은 배열이 있을 때, arr [3]. length의 값은 얼마인가?

int[][] arr = {
	{ 5, 5, 5, 5, 5},
	{ 10, 10, 10},
	{ 20, 20, 20, 20},
	{ 30, 30}
};

2

 

 

 

5-3 배열 arr에 담긴 모든 값을 더하는 프로그램을 완성하시오.

public class JavaExercise5_03 {
	public static void main(String[] args) {
		int[] arr = { 10, 20, 30, 40, 50 };
		int sum = 0;
		/*
			(1) 알맞은 코드를 넣어 완성하시오.
		*/
		System.out.println("sum=" + sum);
	}
}
public class JavaExercise5_3 {
	public static void main(String[] args) {
		int[] arr = { 10, 20, 30, 40, 50 };
		int sum = 0;
		
		for(int i=0;i<arr.length ;i++) {
			sum += arr[i];
		}
		
		System.out.println("sum=" + sum);
	}
}
sum=150

 

 

 

5-4 2차원 배열 arr에 담긴 모든 값의 총합과 평균을 구하는 프로그램을 완성하시오.

public class JavaExercise5_4 {

	public static void main(String[] args) {
		int[][] arr = { 
				{ 5, 5, 5, 5, 5 }, 
				{ 10, 10, 10, 10, 10 }, 
				{ 20, 20, 20, 20, 20 }, 
				{ 30, 30, 30, 30, 30 } };
		int total = 0;
		float average = 0;
		
		for(int i=0;i<arr.length;i++) {
			for(int j=0;j<arr[0].length;j++) {
				total += arr[i][j];
				
			}
		}
        
		/*
			(1) 알맞은 코드를 넣어 완성하시오.
		*/
		
		System.out.println("total=" + total);
		System.out.println("average=" + average);
	} // end of main
} // end of class
public class JavaExercise5_4 {

	public static void main(String[] args) {
		int[][] arr = { 
				{ 5, 5, 5, 5, 5 }, 
				{ 10, 10, 10, 10, 10 }, 
				{ 20, 20, 20, 20, 20 }, 
				{ 30, 30, 30, 30, 30 } };
		int total = 0;
		float average = 0;
		
		for(int i=0;i<arr.length;i++) {
			for(int j=0;j<arr[0].length;j++) {
				total += arr[i][j];
				
			}
		}
		
		average = (float)total /arr.length * arr[0].length;;
		
		
		System.out.println("total=" + total);
		System.out.println("average=" + average);
	} // end of main
} // end of class
total=325
average=16.25

 

 

5-5 다음은 1과 9 사이의 중복되지 않은 숫자로 이루어진 3자리 숫자를 만들어내는 프로그램이다. (1)~(2)에 알맞은 코드를 넣어서 프로그램을 완성하시오.
[참고] Math.random()을 사용했기 때문에 실행결과와 다를 수 있다.

public class JavaExercise5_05 {
	public static void main(String[] args) {
		int[] ballArr = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
		int[] ball3 = new int[3];
		// 배열 ballArr의 임의의 요소를 골라서 위치를 바꾼다.
		for (int i = 0; i < ballArr.length; i++) {
			int j = (int) (Math.random() * ballArr.length);
			int tmp = 0;
			
		/*
			(1) 알맞은 코드를 넣어 완성하시오.
		*/
						
	}
		
	// 배열 ballArr의 앞에서 3개의 수를 배열 ball3로 복사한다.
	/* (2) */
		
		for (int i = 0; i < ball3.length; i++) {
			System.out.print(ball3[i]);
		}
	} // end of main
} // end of class
public class JavaExercise5_5 {
	public static void main(String[] args) {
		int[] ballArr = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
		int[] ball3 = new int[3];
		// 배열 ballArr의 임의의 요소를 골라서 위치를 바꾼다.
		for (int i = 0; i < ballArr.length; i++) {
			int j = (int) (Math.random() * ballArr.length);
			int tmp = 0;
			
			tmp = ballArr[i];
			ballArr[i] = ballArr[j];
			ballArr[j] = tmp;
						
			}
		
		ball3[0] = ballArr[0];
		ball3[1] = ballArr[1];
		ball3[2] = ballArr[2];
		
		for (int i = 0; i < ball3.length; i++) {
			System.out.print(ball3[i]);
		}
	} // end of main
} // end of class
386

 

 

5-6 다음은 거스름돈을 몇 개의 동전으로 지불할 수 있는지를 계산하는 문제이다. 변수 money의 금액을 동전으로 바꾸었을 때 각각 몇 개의 동전이 필요한지 계산해서 출력하라. 단, 가능한 한 적은 수의 동전으로 거슬러 주어야 한다. (1)에 알맞은 코드를 넣어서 프로그램을 완성하시오.
[Hint] 나눗셈 연산자와 나머지 연산자를 사용해야 한다.

public class JavaExercise5_6 {
	public static void main(String args[]) {
		// 큰 금액의 동전을 우선적으로 거슬러 줘야한다.
		int[] coinUnit = { 500, 100, 50, 10 };
        
		int money = 2680;
		System.out.println("money=" + money);
		for (int i = 0; i < coinUnit.length; i++) {
        
		/*
			(1) 알맞은 코드를 넣어 완성하시오.
		*/
		}
	} // main
}
public class JavaExercise5_6 {
	public static void main(String args[]) {
		// 큰 금액의 동전을 우선적으로 거슬러 줘야한다.
		int[] coinUnit = { 500, 100, 50, 10 };
		int money = 2680;
		System.out.println("money=" + money);
		for (int i = 0; i < coinUnit.length; i++) {
		
			System.out.printf("%d거스름 돈: %d", coinUnit[i], money/coinUnit[i]);
			System.out.println();
			money = money-coinUnit[i]*(money/coinUnit[i]);
			
		}
	} // main
}
money=2680
500거스름 돈: 5
100거스름 돈: 1
50거스름 돈: 1
10거스름 돈: 3

 

 

 

5-7 문제 5-6에 동전의 개수를 추가한 프로그램이다. 커맨드 라인으로부터 거슬러 줄 금액을 입력받아 계산한다. 보유한 동전의 개수로 거스름돈을 지불할 수 없으면, ‘거스름돈이 부족합니다.’라고 출력하고 종료한다. 지불할 돈이 충분히 있으면, 거스름돈을 지불한 만큼 가진 돈에서 빼고 남은 동전의 개수를 화면에 출력한다. (1)에 알맞은 코드를 넣어서 프로그램을 완성하시오.

 

public class JavaExercise5_7 {
	public static void main(String args[]) {
		// 문자열을 숫자로 변환한다. 입력한 값이 숫자가 아닐 경우 예외가 발생한다.
		int money = 3120;
		
		System.out.println("money=" + money);
		int[] coinUnit = { 500, 100, 50, 10 }; // 동전의 단위
		int[] coin = { 5, 5, 5, 5 }; // 단위별 동전의 개수
		for (int i = 0; i < coinUnit.length; i++) {
			int coinNum = 0;

			coinNum = money / coinUnit[i];
			if (coin[i] >= coinNum) {
				coin[i] -= coinNum;
			} else {
				coinNum = coin[i];
				coin[i] = 0;
			}
			money -= coinNum * coinUnit[i];

			System.out.println(coinUnit[i] + "원: " + coinNum);
		}
		if (money > 0) {
			System.out.println("거스름돈이 부족합니다.");
			System.exit(0); // 프로그램을 종료한다.
		}
		System.out.println("=남은 동전의 개수 =");
		for (int i = 0; i < coinUnit.length; i++) {
			System.out.println(coinUnit[i] + "원:" + coin[i]);
		}
	} // main
}
money=3120
500원: 5
100원: 5
50원: 2
10원: 2
=남은 동전의 개수 =
500원:0
100원:0
50원:3
10원:3

 

 

 

5-8 다음은 배열 answer에 담긴 데이터를 읽고 각 숫자의 개수를 세어서 개수만큼 ‘*’을 찍어서 그래프를 그리는 프로그램이다. (1)~(2)에 알맞은 코드를 넣어서 완성하시오.

public class JavaExercise5_8 {
	public static void main(String[] args) {

		int[] answer = { 1, 4, 4, 3, 1, 4, 4, 2, 1, 3, 2 };
		int[] counter = new int[4];

		for (int i = 0; i < answer.length; i++) {
			/* (1) 알맞은 코드를 넣어 완성하시오. */
			}
		}
		for (int i = 0; i < counter.length; i++) {
			/*
				(2) 알맞은 코드를 넣어 완성하시오.
			*/
			}
			System.out.println();
		}
	} // end of main
} // end of class
public class JavaExercise5_8 {
	public static void main(String[] args) {

		int[] answer = { 1, 4, 4, 3, 1, 4, 4, 2, 1, 3, 2 };
		int[] counter = new int[4];

		for (int i = 0; i < answer.length; i++) {
			if (answer[i] == 1) {
				counter[0] += 1;
			} else if (answer[i] == 2) {
				counter[1] += 1;
			} else if (answer[i] == 3) {
				counter[2] += 1;
			} else if (answer[i] == 4) {
				counter[3] += 1;
			}
		}
		for (int i = 0; i < counter.length; i++) {
			
			System.out.print(counter[i]);
			for (int j = 0; j < counter[i]; j++) {
				System.out.print("*");
			}
			System.out.println();
		}
	} // end of main
} // end of class
3***
2**
2**
4****

 

 

5-9 주어진 배열을 시계방향으로 90도 회전시켜서 출력하는 프로그램을 완성하시오.

public class JavaExercise5_9 {
	public static void main(String[] args) {
		char[][] star = { 
				{ '*', '*', ' ', ' ', ' ' }, 
				{ '*', '*', ' ', ' ', ' ' }, 
				{ '*', '*', '*', '*', '*' },
				{ '*', '*', '*', '*', '*' } };
		char[][] result = new char[star[0].length][star.length];
		for (int i = 0; i < star.length; i++) {
			for (int j = 0; j < star[i].length; j++) {
				System.out.print(star[i][j]);
			}
			System.out.println();
		}
		System.out.println();
			/*
				(1) 알맞은 코드를 넣어 완성하시오.
			*/
			}
		}
		for (int i = 0; i < result.length; i++) {
			for (int j = 0; j < result[i].length; j++) {
				System.out.print(result[i][j]);
			}
			System.out.println();
		}
	} // end of main
} // end of class
public class JavaExercise5_9 {
	public static void main(String[] args) {
		char[][] star = { 
				{ '*', '*', ' ', ' ', ' ' }, 
				{ '*', '*', ' ', ' ', ' ' }, 
				{ '*', '*', '*', '*', '*' },
				{ '*', '*', '*', '*', '*' } };
		char[][] result = new char[star[0].length][star.length];
		for (int i = 0; i < star.length; i++) {
			for (int j = 0; j < star[i].length; j++) {
				System.out.print(star[i][j]);
			}
			System.out.println();
		}
		System.out.println();
		for (int i = 0; i < star.length; i++) {
			for (int j = 0; j < star[i].length; j++) {
				int x = j;
				int y = star.length-1-i;
				result[x][y]=star[i][j];
			}
		}
		for (int i = 0; i < result.length; i++) {
			for (int j = 0; j < result[i].length; j++) {
				System.out.print(result[i][j]);
			}
			System.out.println();
		}
	} // end of main
} // end of class
**   
**   
*****
*****

****
****
**  
**  
**

 

5-10 다음은 알파벳과 숫자를 아래에 주어진 암호표로 암호화하는 프로그램이다.(1)에 알맞은 코드를 넣어서 완성하시오.

public class JavaExercise5_10 {
	public static void main(String[] args) {
		char[] abcCode = { '`', '~', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '_', '+', '=', '|', '[',
				']', '{', '}', ';', ':', ',', '.', '/' };
		// 0 1 2 3 4 5 6 7 8 9
		char[] numCode = { 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p' };
		String src = "abc123";
		String result = "";
		// 문자열 src의 문자를 charAt()으로 하나씩 읽어서 변환 후 result에 저장
		for (int i = 0; i < src.length(); i++) {
			char ch = src.charAt(i);
			/*
				(1) 알맞은 코드를 넣어 완성하시오.
			*/
			}
		}
		System.out.println("src:" + src);
		System.out.println("result:" + result);
	} // end of main
} // end of class
public class JavaExercise5_10 {
	public static void main(String[] args) {
		char[] abcCode = { '`', '~', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '_', '+', '=', '|', '[',
				']', '{', '}', ';', ':', ',', '.', '/' };
		// 0 1 2 3 4 5 6 7 8 9
		char[] numCode = { 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p' };
		String src = "abc123";
		String result = "";
		// 문자열 src의 문자를 charAt()으로 하나씩 읽어서 변환 후 result에 저장
		for (int i = 0; i < src.length(); i++) {
			char ch = src.charAt(i);
			if ('0' <= ch && ch <= '9') {
				result += numCode[ch - '0'];
			} else if ('a' <= ch && ch <= 'z') {
				result += abcCode[ch - 'a'];
			}
		}
		System.out.println("src:" + src);
		System.out.println("result:" + result);
	} // end of main
} // end of class
src:abc123
result:`~!wer

 

 

5-11 주어진 2차원 배열의 데이터보다 가로와 세로로 1이 더 큰 배열을 생성해서 배열의 행과 열의 마지막 요소에 각 열과 행의 총합을 저장하고 출력하는 프로그램이다. (1)에 알맞은 코드를 넣어서 완성하시오.

public class JavaExercise5_11 {
	public static void main(String[] args) {
		int[][] score = { 
				{ 100, 100, 100 }, 
				{ 20, 20, 20 }, 
				{ 30, 30, 30 }, 
				{ 40, 40, 40 }, 
				{ 50, 50, 50 } };
		int[][] result = new int[score.length + 1][score[0].length + 1];
		for (int i = 0; i < score.length; i++) {
			for (int j = 0; j < score[i].length; j++) {
			/*
				(1) 알맞은 코드를 넣어 완성하시오.
			*/
			}
		}
		for (int i = 0; i < result.length; i++) {
			for (int j = 0; j < result[i].length; j++) {
				System.out.printf("%4d", result[i][j]);
			}
			System.out.println();
		}
	} // main
}
public class JavaExercise5_11 {
	public static void main(String[] args) {
		int[][] score = { 
				{ 100, 100, 100 }, 
				{ 20, 20, 20 }, 
				{ 30, 30, 30 }, 
				{ 40, 40, 40 }, 
				{ 50, 50, 50 } };
		int[][] result = new int[score.length + 1][score[0].length + 1];
		for (int i = 0; i < score.length; i++) {
			for (int j = 0; j < score[i].length; j++) {
				
				result[i][j] = score[i][j];
				
				result[score.length][j] += score[i][j];
				result[i][score[i].length]+= score[i][j]; 
				result[score.length][score[i].length] += score[i][j];
				
			}
		}
		for (int i = 0; i < result.length; i++) {
			for (int j = 0; j < result[i].length; j++) {
				System.out.printf("%4d", result[i][j]);
			}
			System.out.println();
		}
	} // main
}
 100 100 100 300
  20  20  20  60
  30  30  30  90
  40  40  40 120
  50  50  50 150
 240 240 240 720

 

 

 

5-12 예제 5-23을 변경하여, 아래와 같은 결과가 나오도록 하시오.

public class MultiArrEx4 {
	public static void main(String[] args) {
		String[][] words = {
				{"chair", "의자"},
				{"computer", "컴퓨터"},
				{"integer","정수"}
		};
	
		Scanner scanner = new Scanner(System.in);
		
		for(int i=0;i<words.length;i++) {
			System.out.printf("Q%d. %s의 뜻은", i+1, words[i][0]);
			
			String tmp = scanner.nextLine();
			
			if(tmp.contentEquals(words[i][1])) {
				System.out.printf("정답입니다.%n%n");
			} else {
				System.out.printf("틀렸습니다 정답은 %s입니다.%n%n",words[i][i]);
			}
		}scanner.close(); // for
	} // main의 끝
}
public class JavaExercise5_12 {
	public static void main(String[] args) {
		String[][] words = { { "chair", "의자" }, // words[0][0], words[0][1]
				{ "computer", "컴퓨터" }, // words[1][0], words[1][1]
				{ "integer", "정수" } // words[2][0], words[2][1]
		};
		int score = 0; // 맞춘 문제의 수를 저장하기 위한 변수
		Scanner scanner = new Scanner(System.in);
		for (int i = 0; i < words.length; i++) {
			System.out.printf("Q%d. %s의 뜻은?", i + 1, words[i][0]);
			String tmp = scanner.nextLine();
			if (tmp.equals(words[i][1])) {
				System.out.printf("정답입니다.%n%n");
				score++;
			} else {
				System.out.printf("틀렸습니다. 정답은 %s입니다.%n%n", words[i][1]);
			}
		} // for
		System.out.printf("전체 %d문제 중 %d문제 맞추셨습니다.%n", words.length, score);
		scanner.close();
	} // main의 끝
}

 

 

 

5-13 단어의 글자 위치를 섞어서 보여주고 원래의 단어를 맞추는 예제이다. 실행결과와 같이 동작하도록 예제의 빈 곳을 채우시오.

public class JavaExercise5_13 {
	public static void main(String args[]) {
		String[] words = { "television", "computer", "mouse", "phone" };

		Scanner scanner = new Scanner(System.in);

		for (int i = 0; i < words.length; i++) {
			char[] question = words[i].toCharArray(); // String을 char[]로 변환

			/*
			 * (1) 알맞은 코드를 넣어 완성하시오. char배열 question에 담긴 문자의 위치를 임의로 바꾼다.
			 */

			System.out.printf("Q%d. %s의 정답을 입력하세요.>", i + 1, new String(question));
			String answer = scanner.nextLine();
			// trim()으로 answer의 좌우 공백을 제거한 후, equals로 word[i]와 비교
			if (words[i].equals(answer.trim()))
				System.out.printf("맞았습니다.%n%n");
			else
				System.out.printf("틀렸습니다.%n%n");
		}
	} // main의 끝
}
public class JavaExercise5_13 {
	public static void main(String args[]) {
		String[] words = { "television", "computer", "mouse", "phone" };

		Scanner scanner = new Scanner(System.in);

		for (int i = 0; i < words.length; i++) {
			char[] question = words[i].toCharArray(); // String을 char[]로 변환

			for (int j = 0; j < 5; j++) {
				int k = (int) (Math.random() * 4);
				char tmp = question[i];
				question[i] = question[k];
				question[k] = tmp;
			}

			System.out.printf("Q%d. %s의 정답을 입력하세요.>", i + 1, new String(question));
			String answer = scanner.nextLine();
			// trim()으로 answer의 좌우 공백을 제거한 후, equals로 word[i]와 비교
			if (words[i].equals(answer.trim()))
				System.out.printf("맞았습니다.%n%n");
			else
				System.out.printf("틀렸습니다.%n%n");
		}
	} // main의 끝
}
Q1. etlevision의 정답을 입력하세요.>television
맞았습니다.

Q2. computer의 정답을 입력하세요.>computer
맞았습니다.

Q3. mouse의 정답을 입력하세요.>mouse
맞았습니다.

Q4. nhope의 정답을 입력하세요.>phone
맞았습니다.

 

 

 

 

배열의 길이 변경하기

배열은 한번 선언하면 길이를 변경할 수 없다,

따라서 더 큰 길이의 배열을 생성한 뒤 기존의 배열에 저장된 값을 새로운 배열에 복사하면 된다.

배열의 길이를 변경하는 방법:
1. 더 큰 배열을 새로 생성한다.
2. 기존 배열의 내용을 새로운 배열에 복사한다.

새로 배열을 생성해야 하는 상황이 가능한 적게 발생하도록 해야 하며, 기존의 2배 정도의 길이로 생성하는 게 좋다.

 

배열의 초기화

배열은 생성과 동시에 자동적으로 자신의 타입에 해당하는 기본값으로 초기화되므로 배열을 사용하기 전에 따로 초기화를 해주지 않아도 되지만, 원하는 값을 저장하려면 각 요소마다 값을 지정해 줘야 한다.

 

배열의 출력

배열에 저장된 값을 값을 확인할 때도 for문을 사용하면 된다.

 

int[] iArr = { 100, 95, 80, 70, 60,};

// 배열의 요소를 순서대로 하나씩 출력
for(int i=0; i<iArr.length; i++) {
	System.out.print(iArr[i]+",");
}
System.out.println();

 

 

배열의 복사

배열은 한번 생성하면 길이를 변경할 수 없기 때문에 이전 배열로부터 내용을 복사해야 한다.

public class ArrayEx04 {
	public static void main(String[] args) {
		char[] abc = { 'A', 'B', 'C', 'D' };
		char[] num = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
		System.out.println(abc);
		System.out.println(num);
		
		// 배열 abc와 num을 붙여서 하나의 배열(result)로 만든다.
		char[] result = new char[abc.length+num.length];
		System.arraycopy(abc, 0, result, 0, abc.length);
		System.arraycopy(num, 0, result, abc.length, num.length);
		System.out.println(result);
		
		// 배열 abc를 배열 num의 첫 번째 위치부터 배열 abc의 길이만큼 복사
		System.arraycopy(abc,  0,  num,  0,  abc.length);
		System.out.println(num);
		
		// number의 인덱스6 위치에 3개를 보사
		System.arraycopy(abc, 0, num, 6, 3);
		System.out.println(num);
	}
}

 

배열의 활용

public class ArrayEx05 {
	public static void main(String[] args) {
		int sum = 0;
		float average = 0f;

		int[] score = { 100, 88, 100, 100, 90 };

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

		average = sum / (float) score.length;
		System.out.println("총점 : " + sum);
		System.out.println("평균 : " + average);
	}
}
배열에서 총점과 평균을 구하기
총점 : 478
평균 : 95.6

 

 

 

public class ArrayEx06 {
	public static void main(String[] args) {
		int[] score = { 79, 88, 91, 33, 100, 55, 95 };

		int max = score[0];
		int min = score[0];

		for (int i = 1; i < score.length; i++) {
			if (score[i] > max) {
				max = score[i];
			} else if (score[i] < min) {
				min = score[i];
			}
		} // end of for
		System.out.println("최대값 :" + max);
		System.out.println("최소값 :" + min);
	} // end of main
}// end of class
변수 두개를 만들어서 배열의 최댓값, 최솟값저장
최대값 :100
최소값 :33

 

 

임의의 값으로 배열 채우기

import java.util.*;

public class ArrayEx09 {
	public static void main(String[] args) {
		int[] code = {-4, -1, 3, 6, 11};
		int[] arr = new int[10];
		
		for(int i=0; i < arr.length ; i++) {
			int tmp = (int)(Math.random() * code.length);
			arr[i] = code[tmp];
		}
		
		System.out.println(Arrays.toString(arr));
	}
}
배열의 값을 임의로 초기화하는 코드
실행할 때 마다 값이 달라진다

 

[3, -4, 3, 6, -4, -4, 11, -1, -4, 11]

 

 

public class ArrayEx11 {
	public static void main(String[] args) {
		int[] numArr = new int[10];
		int[] counter = new int[10];
		
		for(int i=0; i < numArr.length ; i++) {
			numArr[i] = (int)(Math.random() * 10);
			System.out.print(numArr[i]);
		}
		System.out.println();
		
		for(int i=0; i < numArr.length ; i++) {
			counter[numArr[i]]++;
		}
		
		for (int i=0; i < numArr.length ; i++){
			System.out.println( i +"의 개수 :"+ counter[i]);
		}
	}
}
길이가 10인 배열을 만들고 임의의 값으로 초기한다.
8811991509
0의 개수 :1
1의 개수 :3
2의 개수 :0
3의 개수 :0
4의 개수 :0
5의 개수 :1
6의 개수 :0
7의 개수 :0
8의 개수 :2
9의 개수 :3

'JAVA05강 배열(Array) > 배열(array)' 카테고리의 다른 글

배열(array)  (0) 2021.07.15

배열의 타입이 String인 경우에도 다음과 같이 선언할 수 있다.

String[] name = new String[3];

참조형 변수의 기본 값은 null이므로 각 요소의 값은 null로 초기화된다.

 

자료형 기본값
boolean false
char '\u0000'
byte, short, int 0
long 0L
float 0.0f
double 0.0d 또는 0.0
참조형변수 null

 

String배열의 초기화

String[] name = new String[3];
name[0] = "Kim";
name[1] = "Park";
name[2] = "Yi";

String 배열은 선언한 길이의 0 <= 스트링 길이 <=n-1이며

길이는 0을 포함한 자연수로만 선언이 가능하다. 또한 중괄호{}를 사용해서 간단히 초기화할 수도 있다.

String[] name = new String[]{"Kim", "Park", "Yi"};
String[] name = { "Kim", "Park", "Yi"};

 

Char배열과 String클래스

String클래스는 char배열에 기능(메서드)를 추가한 것이다.

객체지향 언어에서는 데이터와 그에 관련된 기능(메서드)을 하나의 클래스에 묶어서 다룰 수 있게 한다.

char배열과 String클래스는 저장할 수 있는 문자의 수 외에 String객체는 읽을 수만 있을 뿐 내용을 변경할 수 없다.

변경 가능한 문자열을 다루려면, StringBuffer클래스를 사용하면 된다.

 

String클래스의 주요 메서드

 

메서드 설명
char charAt(int index) 문자열에서 해당 위치(index)에 있는 문자를 반환한다.
int length() 문자열의 길이를 반환한다.
String substring(int from, int to) 문자열에서 해당 범위(from~to)에 있는 문자열을 반환한다.
(to는 범위에 포함되지 않음)
boolean equals(Object obj) 문자열의 내용이 obj와 같은지 확인한다. 같으면 true, 다르면 false가 된다.
char[]toCharArray() 문자열을 문자배열(char[])로 변환해서 반환한다.

charAt메서드는 문자열에서 지정된 index에 있는 한 문자를 가져온다.

인덱스index의 값으로 0부터 시작한다.

 

substring()은 문자열의 일부를 뽑아낼 수 있다. 주의할 것은 범위의 끝은 포함되지 않는다.

String str = "ABCDE";
char ch = str.charAt(3);

 

equals()는 문자열의 내용이 같은지 다른지 확인하는 데 사용하며, 대소문자를 구분한다.

만일 대소문자를 구분하지 않고 싶다면 equalsIgnoreCase()를 사용하면 된다.

String str = "abc";
if(str.equals("abc")) //str과 abc가 내용이 같은지 확인한다.

 

char배열과 String클래스의 변환

public class ArrayEx14 {
	public static void main(String[] args) {
		String src = "ABCDE";

		for (int i = 0; i < src.length(); i++) {
			char ch = src.charAt(i); // src의 i번째 문자를 ch에 저장
			System.out.println("src.charAt(" + i + "):" + ch);
		}
			// String을 char[]로 변환
			char[] chArr = src.toCharArray();

			// char배열(char[])을 출력
			System.out.println(chArr);
		}
	}
src.charAt(0):A
src.charAt(1):B
src.charAt(2):C
src.charAt(3):D
src.charAt(4):E
ABCDE

char배열을 String클래스로 변환하거나, 또는 그 반대로 해야 하는 경우가 있다.

그럴 때 위 예시대로 문장을 사용하면 된다.

 

커맨드 라인을 통해 입력받기

Scanner클래스의 nextLine()외에도 화면을 통해 사용자로부터 값을 입력받을 수 있는 간단한 방법이 있다.

커맨드 라인을 입력받는 방법이다.

프로그램을 실행할 때 클래스 이름 뒤에 공백 문자로 구분하여 여러 개의 문자열을 프로그램에 전달할 수 있다.

 

이클립스의 Run > Run Configurations나 

window - 실행 - cmd로 해당 파일의 위치를 열고 java class이름 "abc"

방식으로 실행하면 된다.

 

public class ArrayEx01 {
	public static void main(String[] args) {
		int[] score = new int[5];
		int k = 1;

		score[0] = 50;
		score[1] = 60;
		score[k + 1] = 70; // score[2] = 70
		score[3] = 80;
		score[4] = 90;

		int tmp = score[k + 2] + score[4]; // int tmp = score[3] + score[4]

		// for문으로 배열의 모든 요소를 출력한다.
		for (int i = 0; i < 5; i++) {
			System.out.printf("score[%d]:%d%n", i, score[i]);
		}
			System.out.printf("tmp:%d%n", tmp);
			System.out.printf("score[%d]:%d%n", 7, score[7]);// index의 범위를 벗어난 값);
		}
	}
score[0]:50
score[1]:60
score[2]:70
score[3]:80
score[4]:90
tmp:170
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
	at a210712.ArrayEx01.main(ArrayEx01.java:23)

 

 

 

import java.util.Arrays;

//import java.util.*;	// Arrays.toString()을 사용하기 위해 추가

public class ArrayEx02 {
	public static void main(String[] args) {
		int[] iArr1 = new int[10];
		int[] iArr2 = new int[10];
//		int[] iArr3 = new int[] {100, 95, 80, 70, 60};
		int[] iArr3 = {100, 95, 80, 70, 60};
		char[] chArr = {'a', 'b', 'c', 'd'};
		
		for(int i=0; i < iArr1.length ; i++) {
			iArr1[i] = i +1; // 1~10의 숫자를 순서대로 배열에 넣는다.
			
		}
		for (int i=0; i< iArr2.length ; i++) {
			iArr2[i] = (int)(Math.random()*10) + 1;
		}	
			// 배열에 저장된 값들을 출력한다.
			for(int i=0; i <iArr1.length;i++) {
				System.out.print(iArr1[i]+",");
			}
			System.out.println();System.out.println(Arrays.toString(iArr2));
			System.out.println();System.out.println(Arrays.toString(iArr3));
			System.out.println();System.out.println(Arrays.toString(chArr));
			System.out.println();System.out.println(iArr3);
			System.out.println();System.out.println(chArr);
		}
	}
1,2,3,4,5,6,7,8,9,10,
[5, 7, 10, 6, 3, 5, 3, 1, 8, 2]

[100, 95, 80, 70, 60]

[a, b, c, d]

[I@6d06d69c

abcd

 

 

 

public class ArrayEx03 {
	public static void main(String[] args) {
		int[] arr = new int[5];
		
		// 배열 arr에 1~5를 저장한다.
		for (int i = 0; i < arr.length; i++) {
			arr[i] = i + 1; // 1 2 3 4 5
		}
		System.out.println("[변경전]");
		System.out.println("arr.length: " + arr.length);

		for (int i = 0; i < arr.length; i++) {
			System.out.println("arr[" + i + "]:" + arr[i]);
		}
		int[] tmp = new int[arr.length * 2];

		for (int i = 0; i < arr.length; i++) {
			tmp[i] = arr[i];
		}
		arr = tmp;
		System.out.println("[변경후]");
		System.out.println("arr.length : " + arr.length);

		for (int i = 0; i < arr.length; i++) {
			System.out.println("arr[" + i + "]:" + arr[i]);
		}
	}
}
[변경전]
arr.length: 5
arr[0]:1
arr[1]:2
arr[2]:3
arr[3]:4
arr[4]:5
[변경후]
arr.length : 10
arr[0]:1
arr[1]:2
arr[2]:3
arr[3]:4
arr[4]:5
arr[5]:0
arr[6]:0
arr[7]:0
arr[8]:0
arr[9]:0

 

 

 

public class ArrayEx04 {
	public static void main(String[] args) {
		char[] abc = { 'A', 'B', 'C', 'D' };
		char[] num = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
		System.out.println(abc);
		System.out.println(num);
		
		// 배열 abc와 num을 붙여서 하나의 배열(result)로 만든다.
		char[] result = new char[abc.length+num.length];
		System.arraycopy(abc, 0, result, 0, abc.length);
		System.arraycopy(num, 0, result, abc.length, num.length);
		System.out.println(result);
		
		// 배열 abc를 배열 num의 첫 번째 위치부터 배열 abc의 길이만큼 복사
		System.arraycopy(abc,  0,  num,  0,  abc.length);
		System.out.println(num);
		
		// number의 인덱스6 위치에 3개를 보사
		System.arraycopy(abc, 0, num, 6, 3);
		System.out.println(num);
	}
}
ABCD
0123456789
ABCD0123456789
ABCD456789
ABCD45ABC9

 

 

 

public class ArrayEx05 {
	public static void main(String[] args) {
		int sum = 0;
		float average = 0f;

		int[] score = { 100, 88, 100, 100, 90 };

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

		average = sum / (float) score.length;
		System.out.println("총점 : " + sum);
		System.out.println("평균 : " + average);
	}
}
총점 : 478
평균 : 95.6

 

 

public class ArrayEx06 {
	public static void main(String[] args) {
		int[] score = { 79, 88, 91, 33, 100, 55, 95 };

		int max = score[0];
		int min = score[0];

		for (int i = 1; i < score.length; i++) {
			if (score[i] > max) {
				max = score[i];
			} else if (score[i] < min) {
				min = score[i];
			}
		} // end of for
		System.out.println("최대값 :" + max);
		System.out.println("최소값 :" + min);
	} // end of main
}// end of class
최대값 :100
최소값 :33

 

 

public class ArrayEx07 {
	public static void main(String[] args) {
		int[] numArr = new int[10];

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

		for (int i = 0; i < 100; i++) {
			int n = (int) (Math.random() * 10);
			int tmp = numArr[0];
			numArr[0] = numArr[n];
			numArr[n] = tmp;
		}
		for (int i = 0; i < numArr.length; i++)
			System.out.print(numArr[i]);
	}
}
0123456789
0324879615

 

 

public class ArrayEx08 {
	public static void main(String[] args) {
		int[] ball = new int[45];

		for (int i = 0; i < ball.length; i++)
			ball[i] = i + 1;

		int temp = 0;
		int j = 0;

		for (int i = 0; i < 6; i++) {
			j = (int) (Math.random() * 45);
			temp = ball[i];
			ball[i] = ball[j];
			ball[j] = temp;
		}
		for (int i = 0; i < 6; i++)
		System.out.printf("ball[%d]=%d%n", i, ball[i]);
	}
}
ball[0]=13
ball[1]=23
ball[2]=9
ball[3]=45
ball[4]=27
ball[5]=4

 

 

 

import java.util.*;

public class ArrayEx09 {
	public static void main(String[] args) {
		int[] code = {-4, -1, 3, 6, 11};
		int[] arr = new int[10];
		
		for(int i=0; i < arr.length ; i++) {
			int tmp = (int)(Math.random() * code.length);
			arr[i] = code[tmp];
		}
		
		System.out.println(Arrays.toString(arr));
	}
}
[11, 6, 11, 11, 11, 3, 11, 6, -1, 11]

 

 

 

 

public class ArrayEx10 {
	public static void main(String[] args) {
		int[] numArr = new int[10];

		for (int i = 0; i < numArr.length; i++) {
			System.out.print(numArr[i] = (int) (Math.random() * 10));
		}
		System.out.println();

		for (int i = 0; i < numArr.length - 1; i++) {
			boolean changed = false;

			for (int j = 0; j < numArr.length - 1 - i; j++) {
				if (numArr[j] > numArr[j + 1]) {
					int temp = numArr[j];
					numArr[j] = numArr[j + 1];
					numArr[j + 1] = temp;
					changed = true;
				}
			}

			if (!changed)
				break;

			for (int k = 0; k < numArr.length; k++)
				System.out.print(numArr[k]);
			System.out.println();
		}

	}
}
3889633208
3886332089
3863320889
3633208889
3332068889
3320368889
3203368889
2033368889
0233368889

 

 

public class ArrayEx11 {
	public static void main(String[] args) {
		int[] numArr = new int[10];
		int[] counter = new int[10];
		
		for(int i=0; i < numArr.length ; i++) {
			numArr[i] = (int)(Math.random() * 10);
			System.out.println(numArr[i]);
		}
		System.out.println();
		
		for(int i=0; i < numArr.length ; i++) {
			counter[numArr[i]]++;
		}
		
		for (int i=0; i < numArr.length ; i++){
			System.out.println( i +"의 개수 :"+ counter[i]);
		}
	}
}
8953030234
0의 개수 :2
1의 개수 :0
2의 개수 :1
3의 개수 :3
4의 개수 :1
5의 개수 :1
6의 개수 :0
7의 개수 :0
8의 개수 :1
9의 개수 :1

 

 

 

public class ArrayEx12 {
	public static void main(String[] args) {
		String[] names = { "Kim", "Park", "Yi" };

		for (int i = 0; i < names.length; i++)
			System.out.println("names[" + i + "]:" + names[i]);

		String tmp = names[2];
		System.out.println("tmp:" + tmp);
		names[0] = "Yu";

		for (String str : names)
			System.out.println(str);
	}
}
names[0]:Kim
names[1]:Park
names[2]:Yi
tmp:Yi
Yu
Park
Yi

 

 

public class ArrayEx13 {
	public static void main(String[] args) {
		char[] hex = { 'C', 'A', 'F', 'E'};
		
		String[] binary = { "0000", "0001", "0010", "0011",
							"0100", "0101", "0110", "0111",
							"1000",	"1001",	"1001",	"1011",
							"1100",	"1101",	"1110",	"1111"};
		
		String result="";
		for(int i=0; i < hex.length ; i++) {
			if(hex[i] >='0' && hex[i] <='9')	{
				result +=binary[hex[i]-'0'];
			}else {
				result +=binary[hex[i]-'A'+10];
			}
		
		}
		System.out.println("hex:"+ new String(hex));
		System.out.println("binary:"+result);
	}
}
hex:CAFE
binary:1100100111111110

 

 

public class ArrayEx14 {
	public static void main(String[] args) {
		String src = "ABCDE";

		for (int i = 0; i < src.length(); i++) {
			char ch = src.charAt(i); // src의 i번째 문자를 ch에 저장
			System.out.println("src.charAt(" + i + "):" + ch);
		}
			// String을 char[]로 변환
			char[] chArr = src.toCharArray();

			// char배열(char[])을 출력
			System.out.println(chArr);
		}
	}
src.charAt(0):A
src.charAt(1):B
src.charAt(2):C
src.charAt(3):D
src.charAt(4):E
ABCDE

 

 

public class ArrayEx15 {
	public static void main(String[] args) {
		String source = "SOSHELP";
		String[] morse = { ".-", "-...", "-.-", "-..", ".",
				 "..-.", "--.", "....", "..", ".---",
				 "-.-", ".-..", "--", "-.", "---",
				 ".--.", "--.-", ".-.", "...", "-",
				 "..-", "...-", ".--", "-..-", "-.--",
				 "--.."};
		
		String result="";
		
		for(int i=0; i< source.length(); i++) {
			result+=morse[source.charAt(i)-'A'];
			}
		System.out.println("source:"+ source);
		System.out.println("morse:"+result);
		}
	}
source:SOSHELP
morse:...---.........-...--.

 

 

 

public class ArrayEx16 {
	public static void main(String[] args) {
		System.out.println("매개변수의 개수:"+args.length);
		for(int i=0; i<args.length;i++) {
			System.out.println("args[" + i + "] = \""+ args[i] + "\"");
		}
	}
}
매개변수의 개수:3
args[0] = "abc"
args[1] = "123"
args[2] = "Hello world"

 

 

 

public class ArrayEx17 {
	public static void main(String[] args) {
		if (args.length !=3) {
			System.out.println("usage: java ArrayEx17 NUM1 OP NUM2");
			System.exit(0);
		}
		
		int num1 = Integer.parseInt(args[0]);
		char op = args[1].charAt(0);
		int num2 = Integer.parseInt(args[2]);
		int result = 0;
		
		switch(op) {
		case '+':
		result = num1 + num2;
			break;
			
		case '-':
		result = num1 - num2;
			break;
		
		case 'x':
			result = num1 * num2;
			break;
			
		case '/':
			result = num1 / num2;
			break;
		default :
			System.out.println("지원되지 않는 연산입니다.");
		}
		System.out.println("결과"+result);
		}
	}
(7+6을 입력함)
결과13

 

 

 

public class ArrayEx18 {
	public static void main(String[] args) {
		int[][] score = { 
				{ 100, 100, 100 }, 
				{ 20, 20, 20 }, 
				{ 30, 30, 30 }, 
				{ 40, 40, 40 } };
		int sum = 0;

		for (int i = 0; i < score.length; i++) {
			for (int j = 0; j < score[i].length; j++) {
				System.out.printf("score[%d][%d]=%d%n", i, j, score[i][j]);
			}
		}
		for (int[] tmp : score) {
			for (int i : tmp) {
				sum += i;
			}
		}
		System.out.println("sum=" + sum);
	}
}
score[0][0]=100
score[0][1]=100
score[0][2]=100
score[1][0]=20
score[1][1]=20
score[1][2]=20
score[2][0]=30
score[2][1]=30
score[2][2]=30
score[3][0]=40
score[3][1]=40
score[3][2]=40
sum=570

 

 

public class ArrayEx19 {
	public static void main(String[] args) {
		int[][] score = {
				{100, 100, 100}
				, {20, 20, 20}
				, {30, 30, 30}
				, {40, 40, 40}
				, {50, 50, 50}
		};
		// 과목별 총점
		int korTotal = 0, engTotal = 0, mathTotal = 0;
		
		System.out.println("번호	국어	영어	수학	총점	평균 ");
		System.out.println("=============================================");
		
		for(int i=0; i< score.length;i++) {
			int sum = 0;
			float avg = 0.0f;
			
			korTotal += score[i][0];
			engTotal += score[i][1];
			mathTotal += score[i][2];
			System.out.printf("%3d", i+1);
			
			for(int j=0; j <score[i].length;j++) {
				sum += score[i][j];
				System.out.printf("%5d", score[i][j]);
			}
			
			avg = sum/(float)score[i].length; //평균계산
			System.out.printf("%5d %5.1f%n", sum, avg);
		}
		System.out.println("=====================================");
		System.out.printf("총점:%d %4d %4d%n",korTotal,engTotal,mathTotal);
	}
}
번호	국어	영어	수학	총점	평균 
=============================================
  1  100  100  100  300 100.0
  2   20   20   20   60  20.0
  3   30   30   30   90  30.0
  4   40   40   40  120  40.0
  5   50   50   50  150  50.0
=====================================
총점:240  240  240

 

 

public class MultiArrEx1 {
	public static void main(String[] args) {
		final int SIZE = 10;
		int x = 0, y = 0;
		
		char[][] board = new char[SIZE][SIZE];
		byte[][] shipBoard = {
				// 1 2 3 4 5 6 7 8 9
				{ 0, 0, 0, 0, 0, 0, 1, 0, 0, }, // 1
				{ 1, 1, 1, 1, 0, 0, 1, 0, 0, }, // 2
				{ 0, 0, 0, 0, 0, 0, 1, 0, 0, }, // 3
				{ 0, 0, 0, 0, 0, 0, 1, 0, 0, }, // 4
				{ 0, 0, 0, 0, 0, 0, 0, 0, 0, }, // 5
				{ 1, 1, 0, 1, 0, 0, 0, 0, 0, }, // 6
				{ 0, 0, 0, 1, 0, 0, 0, 0, 0, }, // 7
				{ 0, 0, 0, 1, 0, 0, 0, 0, 0, }, // 8
				{ 0, 0, 0, 0, 0, 1, 1, 1, 0, }, // 9
		};
		
		// 1행에 행번호를, 1열에 열번호를 저장한다.
		for(int i=1; i<SIZE; i++)
			board[0][i] = board[i][0] = (char)(i+'0');
		
		Scanner scanner = new Scanner(System.in);
		
		while(true) {
			System.out.println("좌표를 입력하세요.(종료는 00)>");
			String input = scanner.nextLine();
			
			if(input.length()==2) {
			x = input.charAt(0) - '0';
			y = input.charAt(1) - '0';
			
			if(x==0 && y==0)
				break;
			}
			
			if(input.length() !=2 || x<=0 || x>=SIZE||y<=0||y>=SIZE) {
				System.out.println("잘못된 입력입니다. 다시 입력해주세요.");
				continue;
			}
			
			// shipBoard[x-1][y-1]의 값이 1이면, 'O'을 board[x][y]에 저장한다.
			board[x][y] =shipBoard[x-1][y-1] ==1 ? 'O' : 'X';
			
			//	배열 board의 내용을 화면에 출력한다.
			for(int i=0;i<SIZE;i++)
				System.out.println(board[i]); // board[i]는 1차원 배열
			System.out.println();
			}
		scanner.close();
		}
	}
좌표를 입력하세요.(종료는 00)>
33

 

 

 

import java.util.Scanner;

public class MultiArrEx2 {
	public static void main(String[] args) {
		final int SIZE = 5;
		int x = 0, y = 0, num = 0;
		
		int[][] bingo = new int[SIZE][SIZE];
		Scanner scanner = new Scanner(System.in);
		
		//배열의 모든 요소를 1부터 SIZE*SIZE까지의 숫자로 초기화
		for(int i=0;i<SIZE;i++)
			for(int j=0;j<SIZE;j++)
				bingo[i][j] = i*SIZE + j +1;
		
		// 배열에 저장된 값을 뒤섞는다.(suffle)
		for(int i=0;i<SIZE;i++) {
			for(int j=0;j<SIZE;j++) {
			x = (int)(Math.random() * SIZE);
			y = (int)(Math.random() * SIZE);
			
			// bingo[i][j]와 임의로 선택된 값(bingo[x][y])을 바꾼다.
			int tmp = bingo[i][j];
			bingo[i][j] = bingo[x][y];
			bingo[x][y] = tmp;
		}
	
	}
		do {
			for(int i=0;i<SIZE;i++) {
				for(int j=0;j<SIZE;j++)
					System.out.printf("%2d ", bingo[i][j]);
				System.out.println();
		}
			System.out.println();
			
			System.out.printf("1~%d의 숫자를 입력하세요.(종료:0)>", SIZE*SIZE);
			String tmp = scanner.nextLine(); // 화면에서 입력받은 내용을 tmp에 저장
			num = Integer.parseInt(tmp);	// 입력받은 문자열(tmp)를 숫자로 변환
			
			// 입력받은 숫자와 같은 숫자가 저장된 요소를 찾아서 0을저장
			outer:
				for(int i=0;i<SIZE;i++) {
					for(int j=0;j<SIZE;j++) {
						if(bingo[i][j]==num) {
							bingo[i][j] = 0;
							break outer; // 2중 반복문을 벗어난다.
						}
					}
				}
			
		} while(num!=0);
		scanner.close();
	} // main의 끝
}
11  8 25  5  3 
 1 10 14 24 20 
16 13 22 18 17 
 6 19 15 21  9 
 2 12  7 23  4 

1~25의 숫자를 입력하세요.(종료:0)>11
 0  8 25  5  3 
 1 10 14 24 20 
16 13 22 18 17 
 6 19 15 21  9 
 2 12  7 23  4 

1~25의 숫자를 입력하세요.(종료:0)>8
 0  0 25  5  3 
 1 10 14 24 20 
16 13 22 18 17 
 6 19 15 21  9 
 2 12  7 23  4 

1~25의 숫자를 입력하세요.(종료:0)>0

 

 

 

public class MultiArrEx3 {
	public static void main(String[] args) {
		int[][] m1 = {
				{1, 2, 3},
				{4, 5, 6}
		};
	
		int[][] m2 = {{1, 2},
				{3, 4},
				{5, 6}
	};
	
	final int ROW	= m1.length;
	final int COL	= m2[0].length;
	final int M2_ROW= m2.length;
	
	int[][] m3 = new int[ROW][COL];
	
	// 행렬곱 m1 x m2의 결과를 m3에 저장
	for(int i=0;i<ROW;i++)
		for(int j=0;j<COL;j++)
			for(int k=0;k<M2_ROW;k++)
				m3[i][j] += m1[i][k] * m2[k][j];
	
	// 행렬 m3를 출력
	for(int i=0;i<ROW;i++) {
		for(int j=0;j<COL;j++) {
			System.out.printf("%3d ", m3[i][j]);
		}
		System.out.println();
		
		}
	} // main의 끝

}
 22  28 
 49  64

 

 

import java.util.Scanner;

public class MultiArrEx4 {
	public static void main(String[] args) {
		String[][] words = {
				{"chair", "의자"},
				{"computer", "컴퓨터"},
				{"integer","정수"}
		};
	
		Scanner scanner = new Scanner(System.in);
		
		for(int i=0;i<words.length;i++) {
			System.out.printf("Q%d. %s의 뜻은", i+1, words[i][0]);
			
			String tmp = scanner.nextLine();
			
			if(tmp.contentEquals(words[i][1])) {
				System.out.printf("정답입니다.%n%n");
			} else {
				System.out.printf("틀렸습니다 정답은 %s입니다.%n%n",words[i][i]);
			}
		}scanner.close(); // for
	} // main의 끝
}
Q1. chair의 뜻은액자
틀렸습니다 정답은 chair입니다.

Q2. computer의 뜻은컴퓨터
정답입니다.

Q3. integer의 뜻은정수
정답입니다.

 

배열이란?

같은 타입의 여러 변수를 하나의 묶음으로 다루는 것을'배열(array)라고 한다.

많은 양의 데이터를 손쉽게 저장하고 다루기 위해 필요하다.

 배열은 '같은 타입'의 여러 변수를 하나의 묶음으로 다루는 것

배열은 각 저장공간이 연속적으로 배치되어 있다는 특징이 있다.

 

배열의 선언과 생성

배열을 선언하는 방법은 원하는 타입의 변수를 선언하고 변수 또는 타입에 배열임을 의미하는 대괄호를 붙이면 된다.

선언방법 선언 예
타입[] 변수이름; int[]     score;
String[] name;
타입 변수이름[]; int     score[];
String name[]

 

배열의 생성

배열을 선언한 다음에는 배열을 생성해야 한다. 배열을 선언하는 것은

생성된 배열을 다루기 위한 참조변수를 위한 공간이 만들어질 뿐이고, 

배열을 생성해야만 비로소 값을 저장할 수 있는 공간이 만들어진다.

타입[]	변수이름;
변수이름 = new 타입[길이];

배열을 생성하기 위해서는 연산자'new'와 함께 배열의 타입과 길이를 지정해 주어야 한다.

 

1. int[] score; //int형 배열 참조변수 score을 선언한다.
2. score = new int [5]; //연산자'new'에 의해서 메모리의 빈 공간에 5개의 int형 데이터를 저장할 수 있는 공간이 마련된다.

 

배열의 길이와 인덱스

생성된 배열의 각 저장공간을 '배열의 요소'라고 하며 '배열 이름[인덱스]의 형식으로 배열의 요소에 접근한다.

인덱스(index)는 배열의 요소마다 붙여진 일렬번호로 각 요소를 구분하는 데 사용된다.

인덱스(index)의 범위는 0부터 '배열길이-1'까지.'

 

배열의 길이

배열을 생성할 때 괄호[]안에 배열의 길이를 적어줘야 하는데, 배열의 길이는 배열의 요소와 개수, 즉 값을 저장할 수 있는 공간의 개수다.

배열의 길이는 양의 정수로 나오며 최댓값은 int타입의 최댓값, 약 20억이다.

 

타입[] 배열 이름 = new 타입[길이];

int arr = new int [];

배열의 길이는 int범위의 양의 정수(0도포함)이어야 한다.

 

배열 이름. length

자바에서는 JVM이 모든 배열의 길이를 별도로 관리하며

'배열 이름. length'를 통해서 배열의 길이에 대한 정보를 얻을 수 있다.

배열은 한번 생성하면 길이를 변경할 수 없기 때문에, 이미 생성된 배열의 길이는 변하지 않는다.

따라서 배열 이름. length는 상수로 변경할 수 없다.

 

'JAVA05강 배열(Array) > 배열(array)' 카테고리의 다른 글

배열(array)의 활용  (0) 2021.07.17

+ Recent posts