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의 뜻은정수
정답입니다.

 

+ Recent posts