class Tv {
	String color;
	boolean power;
	int channel;
	void power() {power = !power;}
	void channelUp() { ++channel;}
	void channelDown() { --channel;}

}

class TvTest{
	public static void main(String[] args) {
		Tv t;
		t = new Tv(); 
		t.channel = 7;
		t.channelDown();
		System.out.println("현재 채널은 " + t.channel + " 입니다.");
	}
}
현재 채널은 6 입니다.

 

 

 

class Tv {
	String color;
	boolean power;
	int channel;
	void power() {power = !power;}
	void channelUp() { ++channel;}
	void channelDown() { --channel;}

}
public class TvTest2 {
	public static void main(String[] args) {
		Tv t1 = new Tv();
		Tv t2 = new Tv();
		System.out.println("t1의 channel값은 " + t1.channel + "입니다:");
		System.out.println("t2의 channel값은 " + t2.channel + "입니다:");
		
		t1.channel = 7;
		System.out.println("t1의 channel값을 7로 변경하였습니다.");
		
		System.out.println("t1의 channel값은 " + t1.channel + "입니다:");
		System.out.println("t2의 channel값은 " + t2.channel + "입니다:");
	}
}
		
		System.out.println("t1의 channel값은 " + t1.channel + "입니다:");
		System.out.println("t2의 channel값은 " + t2.channel + "입니다:");
	}

}
t1의 channel값은 0입니다:
t2의 channel값은 0입니다:
t1의 channel값을 7로 변경하였습니다.
t1의 channel값은 7입니다:
t2의 channel값은 0입니다:

 

 

 

class Tv {
	String color;
	boolean power;
	int channel;
	void power() {power = !power;}
	void channelUp() { ++channel;}
	void channelDown() { --channel;}

}
public class TvTest3 {
	public static void main(String[] args) {
		Tv t1 = new Tv();
		Tv t2 = new Tv();
		
		System.out.println("t1의 channel값은 " + t1.channel + "입니다");
		System.out.println("t2의 channel값은 " + t2.channel + "입니다");
		
		t2 = t1;
		t1.channel = 7;
		System.out.println("t1의 channel값을 7로 변경하였습니다.");
		
		System.out.println("t1의 channel값은 " + t1.channel + "입니다:");
		System.out.println("t2의 channel값은 " + t2.channel + "입니다:");
		
		Tv[] tvArr = new Tv[3];
		tvArr[0].channel = 10;
	}
}
t1의 channel값은 0입니다
t2의 channel값은 0입니다
t1의 channel값을 7로 변경하였습니다.
t1의 channel값은 7입니다:
t2의 channel값은 7입니다:

 

 

 

public class TvTest4 {
	public static void main(String[] args) {
		Tv[] tvArr = new Tv[3];
		
		for(int i=0; i <tvArr.length;i++) {
			tvArr[i] = new Tv();
			tvArr[i].channel = i+10;
		}
		
		for(int i=0; i<tvArr.length;i++) {
			tvArr[i].channelUp();
			System.out.printf("tvArr[%d].channel=%d%n",i,tvArr[i].channel);
		}
	}
}
class Tv {
	String color;
	boolean power;
	int channel;
	void power() {power = !power;}
	void channelUp() { ++channel;}
	void channelDown() { --channel;}

}
tvArr[0].channel=11
tvArr[1].channel=12
tvArr[2].channel=13

 

 

public class CardTest {
	public static void main(String[] args) {
		System.out.println("Card.width = " + Card.width);
		System.out.println("Card.width = " + Card.height);
		
		Card c1 = new Card();
		c1.kind = "Heart";
		c1.number = 7;
		
		Card c2 = new Card();
		c2.kind = "Spade";
		c2.number = 4;
		
		System.out.println("c1은 " + c1.kind + ", " + c1.number + "이며, 크기는 (" + c1.width + ", " + c1.height + ")");
		System.out.println("c2은 " + c2.kind + ", " + c2.number + "이며, 크기는 (" + c2.width + ", " + c2.height + ")"); //c1 c2를Card로 바꿔도 값이 같다
		System.out.println("c1의 width와 height를 각각 50, 80으로 변경합니다.");
		
		c1.width = 50;
		c1.height = 80;
		
		System.out.println("c1은 " + c1.kind + ", " + c1.number + "이며, 크기는 (" + c1.width + ", " + c1.height + ")") ;
		System.out.println("c2은 " + c2.kind + ", " + c2.number + "이며, 크기는 (" + c2.width + ", " + c2.height + ")") ;
	}
}
class Card {
	String kind;
	int number;
	static int width = 100;
	static int height = 250;
}
Card.width = 100
Card.width = 250
c1은 Heart, 7이며, 크기는 (100, 250)
c2은 Spade, 4이며, 크기는 (100, 250)
c1의 width와 height를 각각 50, 80으로 변경합니다.
c1은 Heart, 7이며, 크기는 (50, 80)
c2은 Spade, 4이며, 크기는 (50, 80)

 

 

 

public class MyMathTest {
	public static void main(String[] args) {
		MyMath mm = new MyMath();
		
		long result1 = mm.add(5L, 3L);
		long result2 = mm.subtract(5L, 3L);
		long result3 = mm.multiply(5L, 3L);
		double result4 = mm.divide(5L, 3L);
		
		System.out.println("add(5L, 3L) = " + result1);
		System.out.println("subtract(5L, 3L) = " + result2);
		System.out.println("multiply(5L, 3L) = " + result3);
		System.out.println("divide(5L, 3L) = " + result4);
	}
}

class MyMath {long add(long a, long b) {
	long result = a+b;
	return result;
	}
	long subtract(long a, long b) {return a -b;}
	long multiply(long a, long b) { return a * b;}
	double divide(double a, double b) {return a / b;}
}
add(5L, 3L) = 8
subtract(5L, 3L) = 2
multiply(5L, 3L) = 15
divide(5L, 3L) = 1.6666666666666667

 

 

 

public class CallStackTest {
	public static void main(String[] args) {
		firstMethod();
	}
	static void firstMethod() {
		secondMethod();
	}
	static void secondMethod() {
		System.out.println("secondMethod()");
	}
}
secondMethod()

 

 

public class CallStackTest2 {
	public static void main(String[] args) {
		System.out.println("main(String[] args)이 시작되었음.");
		firstMethod();
		System.out.println();
	}
	static void firstMethod() {
		System.out.println("firstMethod()이 시작되었음.");
		secondMethod();
		System.out.println("firstMethod()이 끝났음.");
	}
	static void secondMethod() {
		System.out.println("secondMethod()이 시작되었음.");
		System.out.println("secondMethod()이 끝났음.");
	}
}
main(String[] args)이 시작되었음.
firstMethod()이 시작되었음.
secondMethod()이 시작되었음.
secondMethod()이 끝났음.
firstMethod()이 끝났음.

 

 

public class PrimitiveParamEx {
	public static void main(String[] args) {
		Data d = new Data();
		d.x = 10;
		System.out.println("main() : x = " + d.x);
		
		change(d.x);
		System.out.println("After change(d.x)");
		System.out.println("main() : x = " + d.x);
		
	}
	static void change(int x) {
		x = 1000;
		System.out.println("change1() : x = " + x);
	}
}
main() : x = 10
change1() : x = 1000
After change(d.x)
main() : x = 10

 

 

 

public class ReferenceParamEx {
	public static void main(String[] args) {
		Data d = new Data();
		d.x = 10;
		System.out.println("main() : x = " + d.x);

	}

	static void change(Data d) {
		d.x = 1000;
		System.out.println("change() : x = " + d.x);

	}
}
main() : x = 10

 

public class ReferenceParamEx2 {
	public static void main(String[] args) {
		int[] x = {10};
		System.out.println("main() : x = "+ x[0]);
		
		change(x);
		System.out.println("After change(x)");
		System.out.println("main() : x = "+ x[0]);
	}
	
	static void change(int[] x) {
		x[0] = 1000;
		System.out.println("change() : x = " +x[0]);
	}
}
main() : x = 10
change() : x = 1000
After change(x)
main() : x = 1000

 

 

 

public class ReturnTest {
	public static void main(String[] args) {
		ReturnTest r = new ReturnTest();

		int result = r.add(3, 5);
		System.out.println(result);

		int[] result2 = { 0 };
		r.add(3, 5, result2);
		System.out.println(result2[0]);
	}

	int add(int a, int b) {
		return a + b;
	}

	void add(int a, int b, int[] result) {
		result[0] = a + b;
	}
}

 

 

 

 

class Date {int x;}

public class ReferenceReturnEx_1 {
	public static void main(String[] args) {
		Date d = new Date();
		d.x = 10;
		
		Date d2 = copy(d);
		
		System.out.println("d.x ="+d.x);
		System.out.println("d2.x="+d2.x);
	}

	static Date copy(Date Date) {
		Date tmp = new Date();
		tmp.x = Date.x;
		
		return tmp;
	}
}
d.x =10
d2.x=10

 

 

 

public class FactorialTest {
	public static void main(String[] args) {
		int result = factorial(4);
		
		System.out.println(result);
		
	}
	
	static int factorial(int n) {
		int result=0;
		if(n==1)
			result = 1;
		else
			result = n * factorial(n-1);
		
		return result;
	}
}
24

 

 

 

public class FactorialTest2 {
	static long factorial(int n) {
		if(n<=0 || n>20) return -1;
		if(n<=1) return 1;
		return n * factorial(n-1);
	}
	
	public static void main(String[] args) {
		int n =21;
		long result = 0;
		
		for(int i = 1; i <= n; i++) {
			result = factorial(i);
			
			if(result==-1) {
				System.out.printf("유효하지 않은 값입니다.(0<n<=20):%d%n", n);
				break;
			}
			
			System.out.printf("%2d!=%20d%n", i, result);
		}
	}
}
 1!=                   1
 2!=                   2
 3!=                   6
 4!=                  24
 5!=                 120
 6!=                 720
 7!=                5040
 8!=               40320
 9!=              362880
10!=             3628800
11!=            39916800
12!=           479001600
13!=          6227020800
14!=         87178291200
15!=       1307674368000
16!=      20922789888000
17!=     355687428096000
18!=    6402373705728000
19!=  121645100408832000
20!= 2432902008176640000
유효하지 않은 값입니다.(0<n<=20):21

 

 

 

public class MainTest {
	public static void main(String[] args) {
		main(null);
	}
}
Exception in thread "main" java.lang.StackOverflowError
	at a210715.MainTest.main(MainTest.java:5)
	at a210715.MainTest.main(MainTest.java:5)
    ...
	at a210715.MainTest.main(MainTest.java:5)
	at a210715.MainTest.main(MainTest.java:5)
	at a210715.MainTest.main(MainTest.java:5)

 

 

 

public class PowerTest {
	public static void main(String[] args) {
		int x = 2;
		int n = 5;
		long result = 0;
		
		for(int i=1; i<=n; i++) {
			result += power(x, i);
		}
		System.out.println(result);
	}
	
	static long power (int x, int n) {
		if(n==1) return x;
		return x * power(x, n-1);
	}
}
62

 

 

 

class MyMath2 {
	long a, b;
	
	long add()		{ return a + b;	}
	long subtract()	{ return a - b;	}
	long multiply()	{ return a * b;	}
	double divide()	{ return a / b;	}
	
	static long		add(long a, long b)			{ return a + b;	}
	static long		subtract(long a, long b)	{ return a - b;	}
	static long		multiply(long a, long b)	{ return a * b;	}
	static double	divide(double a, double b)	{ return a / b;	}
}

class MyMathTest2 {
	public static void main(String[] args) {
		System.out.println(MyMath2.add(200L, 100L));
		System.out.println(MyMath2.subtract(200L, 100L));
		System.out.println(MyMath2.multiply(200L, 100L));
		System.out.println(MyMath2.divide(200.0, 100.0));
		
		MyMath2 mm = new MyMath2();
		mm.a = 200L;
		mm.b = 100L;
		
		System.out.println(mm.add());
		System.out.println(mm.subtract());
		System.out.println(mm.multiply());
		System.out.println(mm.divide());
	}
}
300
100
20000
2.0
300
100
20000
2.0

 

 

 

public class OverloadingTest {
	public static void main(String[] args) {
		MyMath3 mm = new MyMath3();
		System.out.println("mm.add(3, 3) 결과:" + mm.add(3,3));
		System.out.println("mm.add(3L, 3) 결과: " + mm.add(3L,3));
		System.out.println("mm.add(3, 3L) 결과: " + mm.add(3,3L));
		System.out.println("mm.add(3L, 3L) 결과: " + mm.add(3L,3L));
		
		int[] a = {100, 200, 300};
		System.out.println("mm.add(a) 결과: " + mm.add(a));
	}

}

class MyMath3 {
	int add(int a, int b) {
		System.out.print("int add(int a, int b) -");
		return a+b;
	}
	
	long add(int a, long b) {
		System.out.print("long add(int a, long b) - ");
		return a+b;
	}
	
	long add(long a, int b) {
		System.out.print("long add(long a, int b) - ");
		return a+b;
	}
	long add(long a, long b) {
		System.out.print("long add(long a, long b) - ");
		return a+b;
	}
	int add(int[] a ) {
		System.out.print("int add(int[] a) - ");
		int result = 0;
		for(int i=0; i < a.length;i++) {
			result +=a[i];
		}
		return result;
	}
}
int add(int a, int b) -mm.add(3, 3) 결과:6
long add(long a, int b) - mm.add(3L, 3) 결과: 6
long add(int a, long b) - mm.add(3, 3L) 결과: 6
long add(long a, long b) - mm.add(3L, 3L) 결과: 6
int add(int[] a) - mm.add(a) 결과: 600

 

 

 

public class VarArgsEx {
	public static void main(String[] args) {
		String[] strArr = { "100", "200", "300"	};
		
		System.out.println(concatenate("", "100", "200", "300"));
		System.out.println(concatenate("-", strArr));
		System.out.println(concatenate(",", new String[] {"1", "2", "3"}));
		System.out.println("["+concatenate(",", new String[0])+"]");
		System.out.println("["+concatenate(",")+"]");
	}
	
	static	String concatenate(String delim, String...args) {
		String result = "";
		
		for(String str : args) {
			result += str + delim;
		}
		
		return result;
	}
//	
//	static String concatenate(String...strings args) {
//		return concatenate("", args);
//	}
	
}
100200300
100-200-300-
1,2,3,
[]
[]

 

 

 

public class ConstructorTest {
	public static void main(String[] args) {
		Data1 d1 = new Data1();
		Data2 d2 = new Data2();	//오류를 고치기 위해 int타입의 인자를 기입해주면된다.
		System.out.println(d2.value);
	}
}

class Data1 {
	int value;
	Data1() {} //생성자가 기본으로 만들어져있음
	
}

class Data2 {
	int value;
	Data2(){}  //6번줄의 오류를 고치기 위해생성자를만들어줌 즉 초기화를시킴
	
	Data2(int x) {
		value = x;
	}
}
0

 

 

 

class Car {
	String color;
	String gearType;
	int door;
	
	Car(){}
	Car(String c, String g, int d) {
		color = c;
		gearType = g;
		door = d;
	}
}
public class CarTest {
	public static void main(String[] args) {
		Car c1 = new Car();
		c1.color	= "white";
		c1.gearType	= "auto";
		c1.door 	= 4;
		
		Car c2	= new Car("white", "auto", 4);
		
		System.out.println("c1의 color=" + c1.color + ", gearType=" +c1.gearType+ ", door"+c1.door);
		System.out.println("c2의 color=" + c2.color + ", gearType=" +c2.gearType+ ", door"+c2.door);
	}
}
c1의 color=white, gearType=auto, door4
c2의 color=white, gearType=auto, door4

 

 

 

class Car {
	String color;
	String gearType;
	int door;
	
	Car() {
		this("white", "auto", 4);
	}

	Car(String color) {
			this(color, "auto", 4);
		}
		Car(String color, String gearType, int door) {
			this.color = color;
			this.gearType = gearType;
			this.door = door;
		}
		Car(Car c) {
			color = c.color;
			gearType = c.gearType;
			door = c.door;
		}
}

public class CarTest2 {
	public static void main(String[] args) {
		Car c1 = new Car();
		Car c2 = new Car("blue");
		
		System.out.println("c1의 color=" + c1.color + ", gearType=" + c1.gearType+ ", door="+c1.door);
		System.out.println("c2의 color=" + c2.color + ", gearType=" + c2.gearType+ ", door="+c2.door);
		
	}
}
c1의 color=white, gearType=auto, door=4
c2의 color=blue, gearType=auto, door=4

 

 

 

class Car {
	String color;
	String gearType;
	int door;

	Car() {
		this("white", "auto", 4);
	}

	Car(Car c) {
		color = c.color;
		gearType = c.gearType;
		door = c.door;
	}

	Car(String color, String gearType, int door) {
		this.gearType = gearType;
		this.door = door;
	}
}

class CarTest3 {
	public static void main(String[] args) {
		Car c1 = new Car();
		Car c2 = new Car(c1);
		System.out.println("c1의 color=" + c1.color + ", gearType=" + c1.gearType + ", door" + c1.door);
		System.out.println("c1의 color=" + c1.color + ", gearType=" + c1.gearType + ", door" + c1.door);
		c1.door = 100;
		System.out.println("c1.door=100; 수행 후");
		System.out.println("c1의 color=" + c1.color + ", gearType=" + c1.gearType + ", door=" + c1.door);
		System.out.println("c2의 color=" + c2.color + ", gearType=" + c2.gearType + ", door=" + c2.door);
	}
}
c1의 color=null, gearType=auto, door4
c1의 color=null, gearType=auto, door4
c1.door=100; 수행 후
c1의 color=null, gearType=auto, door=100
c2의 color=null, gearType=auto, door=4

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
맞았습니다.

 

 

 

 

+ Recent posts