public class radi {
	public static void main(String[] args) {
		int rad = 3;
		System.out.println(Math.PI);
		System.out.printf("원 둘레는 : %fcm%n" , Math.PI *2*rad);
		System.out.printf("원 넓이는 : %fcm^2%n" , Math.PI *rad*rad);
	}
}
원 둘레는 : 18.849556cm
원 넓이는 : 28.274334cm^2

3-1 다음 연산의 결과를 적으시오

class Exercise3_1 {
	public static void main(String[] args) {
	int x = 2;
		int y = 5;
		char c = 'A'; // 'A'의 문자코드는 65
		System.out.println(1 + x << 33);
		System.out.println(y >= 5 || x < 0 && x > 2);
		System.out.println(y += 10 - x++);
		System.out.println(x+=2);
		System.out.println( !('A' <= c && c <='Z') );
		System.out.println('C'-c);
		System.out.println('5'-'0');
		System.out.println(c+1);
		System.out.println(++c);
		System.out.println(c++);
		System.out.println(c);
	}
}
6
true
13
5
false
2
5
66
B
B
C

<<는 쉬프트 연산자이고 int는 8*4=32이므로 왼쪽으로 한번 쉬프트 된다.

0011 > 0110 따라서 6을 값으로 가진다.

 

&&연산자 x > 2는 x <0 거짓이므로 y >=5 || (거짓)이 되고 y는 5보다 크므로 참을 반환한다.

 

y += 10 - x++ 은 y = y+10-x++이고 x의 println이 끝나고 연산되므로 y = 5 + 10 - 2 즉 13이 된다.

 

x = x+2인데 위에서 x의 값이 3이 되었으므로 x = 3+2 즉 5가 된다.

 

!(65 <= 65 <= 90) 괄호 안은 참이나,! 가 붙어서 출력되므로 거짓 

 

67-65 = 2

 

53-48=5

 

65+1=66

 

65+1=66 (A 다음의 문자 B가 된다) ' '가없으므로 문자로 출력한다

 

++c은 전열 연산자로 이번 연산에 1을 추가한다 따라서 65+1=66

 

c++은 후열 연산자로 다음 연산에 1을 추가한다 따라서 65

 

위 연산에서 후열 연산자를 사용했으므로 65+1=66 

 

 

 

3-2 아래의 코드는 사과를 담는데 필요한 바구니(버켓)의 수를 구하는 코드이다. 만일 사과의 수가 123개이고 하나의 바구니에는 10개의 사과를 담을 수 있다면, 13개의 바구니가 필요할 것이다. (1)에 알맞은 코드를 넣으시오.

public class Exercise3_2 {
	public static void main(String[] args) {
		int numOfApples = 123; // 사과의 개수
		int sizeOfBucket = 10; // 바구니의 크기(바구니에 담을 수 있는 사과의 개수)
		int numOfBucket = ( /* (1) */ ); // 모든 사과를 담는데 필요한 바구니의 수


		System.out.println("필요한 바구니의 수 :"+numOfBucket1);	//?
		}
}
int numOfBucket =
numOfApples/sizeOfBucket + (numOfApples%sizeOfBucket > 0 ? 1 : 0) ;

풀이 1 사과의 수/바구니 크기 + (사과의 수/나머지가 0이 아니면 1)

int numOfBucket = 
((numOfApples-1)/sizeOfBucket)+1;

풀이 2 (사과의 수 -1) 사과의 수는 어차피 자연수이므로 일의 자리 숫자가 0으로 끝나면 이 식으로 필요한 개수가 출력이 된다.

int numOfBucket1 =
(int)Math.ceil((float)numOfApples / sizeOfBucket);

풀이 3 Math.ceil함수를 사용해서 올림 해서 123/10을 12.3으로 계산한 뒤 13으로 올림 해서 출력한다.

필요한 바구니의 수 :13

결과(공통)

 

 

3-3 아래는 변수 num의 값에 따라 ‘양수’, ‘음수’, ‘0’을 출력하는 코드이다. 삼항 연산자를 이용해서 (1)에 알맞은 코드를 넣으시오.

public class Exercise3_3 {
	public static void main(String[] args) {
		int num = 10;
		System.out.println(/* (1) */);
	}
}
num > 0 ? "양수" : (num < 0 ? "음수" : "0")

(조건식)? (참일 시 실행) : (거짓일 때 실행)

양수

 

 

3-4 아래는 변수 num의 값 중에서 백의 자리 이하를 버리는 코드이다. 만일 변수 num의 값이 ‘456’이라면 ‘400’이 되고, ‘111’이라면 ‘100’이 된다. (1)에 알맞은 코드를 넣으시오.

public class Exercise3_4 {
	public static void main(String[] args) {
		int num = 456;
		System.out.println( /* (1) */ );
	}
}
num/100 * 100

456을 100으로 나누면 소수점은 int타입이라 없어지므로 4가 되고 거기서 다시 100을 곱한다.

400

 

public class Exercise3_4_1 {
	public static void main(String[] args) {
		double num1 = 456;
		double a= Math.floor(num1/100)*100;
		System.out.println(a);
	}
}
400.0

double타입일때 계산법 내림 함수를 이용한다.

 

 

 

3-5 아래는 변수 num의 값 중에서 일의 자리를 1로 바꾸는 코드이다. 만일 변수 num의 값이 333이라면 331이 되고, 777이라면 771이 된다. (1)에 알맞은 코드를 넣으시오.

public class Exercise3_5 {
	public static void main(String[] args) {
		int num = 333;
		System.out.println( /* (1) */ );
	}
}
num/10*10+1

1의 자리를 버리고 1을 더한다.

331

 

public class Exercise3_5_1 {
	public static void main(String[] args) {
		double num1 = 333;
		double n1 = Math.floor(num1/10)*10+1;
		System.out.println( n1 );
	}
}

내림함수를 사용한다.

331.0

 

 

3-6 아래는 변수 num의 값보다 크면서도 가장 가까운 10의 배수에서 변수 num의 값을 뺀 나머지를 구하는 코드이다. 예를 들어, 24의 크면서도 가장 가까운 10의 배수는 30이다. 19의 경우 20이고, 81의 경우 90이 된다. 30에서 24를 뺀 나머지는 6이기 때문에 변수 num의 값이 24라면 6을 결과로 얻어야 한다. (1)에 알맞은 코드를 넣으시오.
[Hint] 나머지 연산자를 사용하라.

public class Exercise3_6 {
	public static void main(String[] args) {
		int num = 24;
		System.out.println((/* (1) */);
	}
}
(num / 10 + 1) * 10 - num)

(1의자리 버림 연산+10)-24

6

 

		System.out.println(10 - (num % 10));

10에서 나머지를 빼버림

6

 

public class Exercise3_6_1 {
	public static void main(String[] args) {
		double num = 24;
		System.out.println((Math.floor(num / 10+1) * 10 - num));
	}
}

함수 사용

6.0

 

 

3-7 아래는 화씨(Fahrenheit)를 섭씨(Celcius)로 변환하는 코드이다. 변환 공식이 'C = 5/9 ×(F - 32)'라고 할 때, (1)에 알맞은 코드를 넣으시오. 단, 변환 결괏값은 소수점 셋째 자리에서 반올림해야 한다.

(Math.round()를 사용하지 않고 처리할 것)

public class Exercise3_7 {
	public static void main(String[] args) {
		int fahrenheit = 100;
		float celcius = ( /* (1) */ );
		System.out.println("Fahrenheit:" + fahrenheit);
		System.out.println(String.format("%.2f", celcius));
	}
}
(int)((5/9f * (fahrenheit - 32))*100 + 0.5) / 100f;

인트의 버림을 이용함

float celcius = 5 / 9f * (fahrenheit - 32);
Fahrenheit:100
37.78

 

 

3-8 아래 코드의 문제점을 수정해서 실행결과와 같은 결과를 얻도록 하시오.

public class Exercise3_8 {
	public static void main(String[] args) {
		byte a = 10;
		byte b = 20;
		byte c = a + b;
		char ch = 'A';
		ch = ch + 2;
		float f = 3f / 2;
		long l = 3000 * 3000 * 3000;
		float f2 = 0.1f;
		double d = 0.1;
		boolean result = d == f2;
		System.out.println("c=" + c);
		System.out.println("ch=" + ch);
		System.out.println("f=" + f);
		System.out.println("l=" + l);
		System.out.println("result=" + result);
	}
}
public class Exercise3_8 {
	public static void main(String[] args) {
		byte a = 10;
		byte b = 20;
		byte c = (byte) (a + b);
		char ch = 'A';
		ch = (char) (ch + 2);
		float f = 3f / 2;
		long l = 3000L * 3000 * 3000;
		float f2 = 0.1f;
		double d = 0.1f;
		boolean result = d == f2;
		System.out.println("c=" + c);
		System.out.println("ch=" + ch);
		System.out.println("f=" + f);
		System.out.println("l=" + l);
		System.out.println("result=" + result);
	}
}

계산은 int형으로 계산하므로 앞에 형 변환을 해줘야 한다.

float이나 long타입으로 계산하고 싶다면 f나 L을 붙여줘야 한다.

double과 float는 부동소수 형태를 받아야 데이터 손실이 나지 않는다.

c=30
ch=C
f=1.5
l=27000000000
result=true

 

3-9 다음은 문자형 변수 ch가 영문자(대문자 또는 소문자)이거나 숫자일 때만 변수 b의 값이 true가 되도록 하는 코드이다. (1)에 알맞은 코드를 넣으시오.

public class Exercise3_9 {
	public static void main(String[] args) {
		char ch = 'z';
		boolean b = (/* (1) */);
	}
}
(ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')
true

 

3-10 다음은 대문자를 소문자로 변경하는 코드인데, 문자 ch에 저장된 문자가 대문자인 경우에만 소문자로 변경한다. 문자코드는 소문자가 대문자보다 32만큼 더 크다. 예를 들어 'A‘의 코드는 65이고 ’a'의 코드는 97이다. (1)~(2)에 알맞은 코드를 넣으시오.

public class Exercise3_10 {
	public static void main(String[] args) {
		char ch = 'A';
		char lowerCase = ( /* (1) */ ) ? ( /* (2) */ ) : ch;
		System.out.println("ch:" + ch);
		System.out.println("ch to lowerCase:" + lowerCase);

	}
}
(ch >= 'A' && ch <= 'Z') ? (lowerCase = (char)( ch + 32)) : ch;
ch:A
ch to lowerCase:a

배열의 타입이 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

break문은 근접한 단 하나의 반복문만 벗어날 수 있기 때문에, 여러 개의 반복문이 중첩된 경우에는 break문으로 중첩된 반복문을 완전히 벗어날 수 없다. 이때 이름 붙은 반복문으로 하나 이상의 반복문을 벗어나거나 반복을 건너뛸 수 있다.

 

public class FlowEx33 {
	public static void main(String[] args) {
		// for문에 Loop1이라는 이름을 붙였다.
		Loop1:
			for (int i = 2; i <= 9; i++) {
			for (int j = 1; j <= 9; j++) {
				if (j == 5)
//				break Loop1;
//				break;
//				continue Loop1;
				continue;
				System.out.println(i + "*" + j + "=" + i * j);
			} // end of for i
			System.out.println();
		} // end of Loop1
	}
}
2*1=2
2*2=4
2*3=6
2*4=8
2*6=12
2*7=14
2*8=16
2*9=18

3*1=3
3*2=6
3*3=9
3*4=12
3*6=18
3*7=21
3*8=24
3*9=27

4*1=4
4*2=8
4*3=12
4*4=16
4*6=24
4*7=28
4*8=32
4*9=36

5*1=5
5*2=10
5*3=15
5*4=20
5*6=30
5*7=35
5*8=40
5*9=45

6*1=6
6*2=12
6*3=18
6*4=24
6*6=36
6*7=42
6*8=48
6*9=54

7*1=7
7*2=14
7*3=21
7*4=28
7*6=42
7*7=49
7*8=56
7*9=63

8*1=8
8*2=16
8*3=24
8*4=32
8*6=48
8*7=56
8*8=64
8*9=72

9*1=9
9*2=18
9*3=27
9*4=36
9*6=54
9*7=63
9*8=72
9*9=81

 

i * 5의 식이 생략되었다.

 

public class FlowEx34 {
	public static void main(String[] args) {
		int menu = 0, num = 0;
		
		Scanner scanner = new Scanner(System.in);
		
		outer:
			while(true) {
				System.out.println("(1) square");
				System.out.println("(2) square root");
				System.out.println("(3) log");
				System.out.println("원하는 메뉴(1~3)를 선택하세요.(종료0)>");
				
				String tmp = scanner.nextLine();	// 화면에서 입력받은 내용을 tmp에 저장
				menu = Integer.parseInt(tmp);		// 입력받은 문자열(tmp)를 숫자로 변환
				
				if(menu==0) {
					System.out.println("프로그램을 종료합니다.");
					break;
				}else if (!(1<= menu && menu <=3)) {
					System.out.println("메뉴를 잘못 선택하셨습니다.(종료는0)");
					continue;
				}
				
				for(;;) {
					System.out.print("계산할 값을 입력하세요.(계산 종료:0, 전체 종료:99)>");
					tmp = scanner.nextLine();		// 화면에서 입력받은 내용을 tmp에 저장
					num = Integer.parseInt(tmp);	// 입력받은 문자열(tmp)를 숫자로 변환
					
					if(num==0)
						break;
					
					if(num==99)
						break outer;
					
					switch(menu) {
					case 1:
						System.out.println("result="+ num*num);
						break;
					case 2:
						System.out.println("result="+ Math.sqrt(num));
						break;
					case 3:
						System.out.println("result="+ Math.log(num));
						break;
					}
				} // for(;;)
			} // while의 끝
	}// main의 끝
}
(1) square
(2) square root
(3) log
원하는 메뉴(1~3)를 선택하세요.(종료0)>
1
계산할 값을 입력하세요.(계산 종료:0, 전체 종료:99)>2
result=4
계산할 값을 입력하세요.(계산 종료:0, 전체 종료:99)>0
(1) square
(2) square root
(3) log
원하는 메뉴(1~3)를 선택하세요.(종료0)>
2
계산할 값을 입력하세요.(계산 종료:0, 전체 종료:99)>4
result=2.0
계산할 값을 입력하세요.(계산 종료:0, 전체 종료:99)>99

 

예제 4-32에서 코드를 추가한 것이다.

 

반복문만 떼어놓고 보면 무한 반복문인 while문 안에 또 다른 무한 반복문 for문의 중첩된 구조이다.

outer :
while(true) {
	...
    for( ; ; )
    	...
        if(num==0) // 계산 종료. for문을 벗어난다.
        	break;
            if*num==99) // 전체 종료. for문과 while문 모두 벗어난다.
            	break outer;
                ...
            } // for( ; ; )
        } // while(true)

break outer에 의해 for문과 while문 모두를 벗어나 프로그램이 종료된다.

'JAVA 04강 조건문과 반복문 > 반복문break, continue, 명명된반복문' 카테고리의 다른 글

continue문  (0) 2021.07.15
break문  (0) 2021.07.15

continue문은 반복문 내에서만 사용될 수 있으며, 반복이 진행되는 도중에 continue문을 만나면 반복문의 끝으로 이동하여 다음 반복문으로 넘어간다.

for문의 경우 증감식으로 이용하며 while문의 경우 조건식으로 이용한다.

 

import java.util.*;

public class FlowEx32 {
	public static void main(String[] args) {
		int menu = 0;
//		int num = 0;

		Scanner scanner = new Scanner(System.in);

		while (true) {
			System.out.println("(1) square");
			System.out.println("(2) square root");
			System.out.println("(3) log");
			System.out.println("원하는 메뉴(1~3)를 선택하세요. (종료:0)>");

			String tmp = scanner.nextLine();// 화면에서 입력받은 내용을 tmp에 저장
			menu = Integer.parseInt(tmp);

			if (menu == 0) {
				System.out.println("프로그램을 종료합니다.");
				break;
			} else if (!(1 <= menu && menu <= 3)) {
				System.out.println("메뉴를 잘못 선택하셨습니다.(종료는 0)");
				continue;
			}

			System.out.println("선택하신 메뉴는 " + menu + "번입니다.");
		}
		scanner.close();
	}
}
(1) square
(2) square root
(3) log
원하는 메뉴(1~3)를 선택하세요. (종료:0)>
4
메뉴를 잘못 선택하셨습니다.(종료는 0)
(1) square
(2) square root
(3) log
원하는 메뉴(1~3)를 선택하세요. (종료:0)>
1
선택하신 메뉴는 1번입니다.
(1) square
(2) square root
(3) log
원하는 메뉴(1~3)를 선택하세요. (종료:0)>
0
프로그램을 종료합니다.

메뉴를 보여주고 선택하게하는 예제이다.

잘못 선택한경우 다시 while문의 처음으로 돌아간다.

'JAVA 04강 조건문과 반복문 > 반복문break, continue, 명명된반복문' 카테고리의 다른 글

이름 붙은 반복문  (0) 2021.07.15
break문  (0) 2021.07.15

앞서 switch문에서 break문에 대해 배웠던 것 처럼 반복문에서도 break문을 사용할 수 있다.

주로 if문과 함께 사용되어 조건을 만족하면 반복문을 벗어나도록한다.

public class FlowEx30 {
	public static void main(String[] args) {
		int sum = 0;
		int i = 0;
		
		while(true) {
			if(sum > 100)
				break;
			++i;
			sum +=i;
		}// end of while
		
		System.out.println("i=" + i);
		System.out.println("sum=" + sum);
	}
}
i=14
sum=105

숫자를 1부터 더해서 몇까지 더하면 합이 100을넘는지 알아내는 예제이다.

14에서 합105가되어 반복문을 벗어난다.

+ Recent posts