선언 위치에 따른 변수의 종류

변수는 클래스 변수, 인스턴스 변수, 지역변수 모두 세 종류가 있다.

변수의 종류를 결정짓는 중요한 요소는 변수의 선언된 위치이므로 변수의 종류를 파악하기 위해서는 변수가 어느 영역에 선언되었는지를 확인하는 것이 중요하다.

멤버 변수를 제외한 나머지 변수들은 모두 지역변수이며 지금까지 계속 사용해왔다.

멤버 변수 중 static이 붙은 것은 클래스 변수, 붙지 않은 것은 인스턴스 변수이다.

class Variables
{
	int iv;		// 인스턴스변수
    static int cv;	// 클래스변수(static변수, 공유변수)
    
    void method()
	{
    
    	int lv = 0;	// 지역변수
	}
}

 

변수의 종류 선언위치 생성시기
클래스 변수
(class variable)
클래스 영역 클래스가 메모리에 올라갈 때
인스턴스변수
(instance variable)
인스턴스가 생성되었을 때
지역변수
(local variable)
클래스 영역 이외의 영역
(메서드, 생성자, 초기화 블럭 내부)
변수 선언문이 수행되었을 때

 

1. 인스턴스 변수(instance variable)

클래스 영역에 선언되며, 클래스의 인스턴스를 생성할 때 만들어진다.

 

2. 클래스 변수(class variable)

클래스 변수를 선언하는 방법은 인스턴스 변수 앞에 static을 붙이기만 하면 된다.

클래스 변수는 모든 인스턴스가 공통된 저장공간(변수)을 공유하게 된다.

한 클래스의 모든 인스턴스들이 공통적인 값을 유지해야 하는 속성의 경우, 클래스 변수로 선언해야 한다.

클래스 이름. 클래스 변수와 같은 형식으로 사용한다.

 

3 지역변수(local variable)

메서드 지역 내에 선언되어 메서드 내에서만 사용 가능하며, 메서드가 종료되면 소멸되어 사용할 수 없게 된다.

 

클래스 변수와 인스턴스 변수

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 + ")") ;
	}
}

Card클래스의 클래스변수(static변수)인 width, heitht는 Card클래스의 인스턴스를 생성하지 않고도 클래스 이름. 클래스 변수와 같은 방식으로 사용할 수 있다.

Card인스턴스인 c1과 c2는 클래스변수인 width와 height를 공유하기 때문에, c1의 width와 height를 변경하면 c2의 width와 height값도 바뀐 것과 같은 결과를 얻는다.

Card, width, c1.width, c2.width는 모두 같은 저장공간을 참조하므로 항상 같은 값을 같게 된다.

 

클래스 변수를 사용할 때는 Card.width와 같이 클래스이름.클래스변수의 형태로 하는 것이 좋다. 참조변수 c1, c2를 통해서도 클래스변수를 사용할 수 있지만 이렇게 하면 클래스변수를 인스턴스 변수로 오해하기 쉽기 때문이다.

인스턴스변수는 인스턴스가 생성될 때 마다 생성되므로 인스턴스마다 각기 다른 값을 유지할 수 있지만,
클래스 변수는 모든 인스턴스가 하나의 저장공간을 공유하므로, 항상 공통된 값을 갖는다.

 

메서드

메서드는 특정 작업을 수행하는 일련의 문장들을 하나로 묶은 것이다. 기본적으로 수학에서 함수의 역할과 비슷하며

어떤 값을 입력하면 이 값으로 작업을 수행해서 결과를 반환한다. 

예를들면 제곱근을 구하는 메서드 Math.sqrt()에 4.0을 입력하면, 2.0을 결과로반환한다.

 

메서드란것은 작업을 수행하는데 필요한 값을 넣고 원하는 결과를 얻으면 될 뿐, 이 메서드가 내부적으로 어떤 과정을 거쳐 결과를 만들어내는지 전혀 몰라도 된다.

sqrt()외에도 println()이나 random()과 같은 메서드도 마찬가지로 내부동작을 알지 못해도 사용하는데 어려움이 없다.

 

 

 

메서드를 사용하는 이유 

메서드를 통해서 얻는 이점은 여러가지가 있지만 그 중에서 대표적인 세가지는 다음과같다

1. 높은 재사용성(resuability)
	Java API에서 제공하는 메서드와 같이 한번 만들어 놓은 메서드는 몇 번이고 호출할 수 있으며,
    다른 프로그램에서도 사용이 가능하다.
    
2. 중복된 코드의 제거
	반복되는 문장들을 묶어서 하나의 메서드로 작성해 놓으면, 반복되는 문장들 대신
	메서드를 호출하는 한 뭉장으로 대체할 수 있다.
    
3. 프로그램의 구조화
	큰 규모의 프로그램에서는 문장들을 작업단위로 나눠서 여러 개의 메서드에 담아
	프로그램의 구조를 단순화시키는것이 필수적이다.

클래스와 객체의 정의와 용도

클래스랑 객체를 정의해놓은 것 또는 클래스는 객체의 설계도 또는 틀이라고 정의할 수 있다.

클래서의 정의 : 클래스란 객체를 정의해 놓은 것이다.
클래스의 용도 : 클래스는 객체를 생성하는데 사용된다.

 

프로그래밍에서의 객체는 클래스에 정의된 내용대로 메모리에 생성된 것을 뜻한다.

객체의 정의 : 실제로 존재하는 것, 사물 또는 개념
객체의 용도 : 객체가 가지고 있는 기능과 속성에 따라 다름

유형의 객체 : 책상, 의자, 자동차, TV와 같은 사물
무형의 객체 : 수학공식, 프로그램 에러와 같은 논리와 개념

 

 

클래스는 단지 객체를 생성하는 데 사용될 뿐, 객체는 아니다. 원하는 기능의 객체를 사용하기 위해서는 클래스로부터 객체를 먼저 만들어야 한다.

 

클래스 객 체
제품 설계도 제품
TV 설계도 TV
붕어빵 기계 붕어빵

클래스를 잘 만들어 놓으면 객체를 생성할 때마다 고민할 필요 없이 클래스로부터 객체를 생성해서 사용하기만 하면 된다.

 

객체와 인스턴스

클래스로부터 객체를 만드는 과정을 클래스의 인스턴스화(instantiate)라고 하며, 어떤 클래스로부터 만들어진 객체를 그 클래스의 인스턴스(instance)라고 한다.

	인스턴스 화
클래스 -------------> 인스턴스(객체)

 

객체의 구성요소 - 속성과 기능

객체는 속성과 기능, 두 정류의 구성요소로 이루어져 있으며, 일반적으로 객체는 다수의 속성과 다수의 기능을 갖는다.

객체는 속성과 기능의 집합이라고 할 수 있다.

객체가 가지고 있는 속성과 기능을 그 객체의 멤버(구성원, member)라 한다.

속성(property) : 멤버변수(member variable), 특성(attribute), 필드(field), 상태(state)\
기능(function) : 메서드(method), 함수(function), 행위(behavior)

객체지향 프로그래밍에서는 속성과 기능을 각각 변수와 메서드로 표현한다.

속성(property) > 멤버변수(variable)
기능(function) > 메서드(method)

 

 

인스턴스의 생성과 사용

클래스명 변수명;		//클래스의 객체를 참조하기 위한 참조변수를 선언
변수명 = new 클래스명();	// 클래스의 객체를 생성 후, 객체의 주소를 참조변수에 저장

 

 

 

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 입니다.

Tv라는 인스턴스를 생성해서(t = new Tv();)

TvTest라는 메인 메서드에 인스턴스 함수(t.channelDown();)를 호출해서 사용이 가능하다.

 

 

인스턴스는 참조변수를 통해서만 다룰 수 있으며, 참조변수의 타입은 인스턴스의 타입과 일치해야 한다.

 

 

 

클래스의 또 다른 정의

1. 클래스란 - 데이터와 함수의 결합이다.

1. 변수	하나의 데이터를 저장할 수 있는 공간
2. 배열	같은 종류의 여러 데이터를 하나의 집합을 저장할 수 있는 공간
3. 구조체 서로 관련된 여러 데이터를 종류에 관계없이 하나의 집합으로 저장할 수 있는 공간
4. 클래스 데이터와 함수의 결합(구조체 + 함수)

하나의 데이터를 저장하기 위해 변수를, 그리고 같은 종류의 데이터를 보다 효율적으로 다루기 위해서 배열이라는 개념을 도입했으며, 후에 구조체(structure)가 등장하여 자료형의 종류에 상관없이 서로 관계가 깊은 변수들을 하나로 묶어서 다룰 수 있도록 했다.

함수는 주로 데이터를 가지고 작업을 하기 때문에 많은 경우에 있어서 데이터와 함수는 관계가 깊다.

자바와 같은 객체지향 언어에서는 변수(데이터)와 함수를 하나의 클래스에 정의하여 서로가 관계가 깊은 변수와 함수들을 함께 다룰 수 있게 했다.

서로 관련된 변수들을 정의하고 이들에 대한 작업을 수행하는 함수들을 함께 정의한 것이 바로 클래스이다.

C언어에서는 문자열을 문자의 배열로 다루지만, 자바에서는 String이라는 클래스로 문자열을 다룬다.

 

2. 클래스 - 사용자정의 타입(user-defined type)

프로그래밍언어에서 제공하는 자료형(primitive type)외에 프로그래머가 서로 관련된 변수들을 묶어서 하나의 타입으로 새로 추가하는 것을 사용자정의 타입(user-defined type)이라고 한다.

자바에서는 클래스가 곧 사용자정의 타입니다.

 

public class Time {
	private int hour;
	private int minute;
	private float second;
	public int getHHour()	{return hour;	}
	public int getMinute()	{return minute;	}
	public float getSecond()	{return second;}
	
	public void setHour(int h) {
		if ( h < 0 ||h >23) return;
		hour = h;

}

	public void setMinute(int m) {
		if (m < 0 || m >59) return;
		minute = 0;
	}
	
	public void setSecond(float s) {
		if (s < 0.0f || s >59.99f) return;
		second=s;
	}
}

시간이란 class를 정의하고 조건에따라 조건에따라 값을 반환한다.

객체지향 언어의 역사

초창기에 컴퓨터는 과학실험이나 미사일 발사 실험 같은 모의실험을 목적으로 사용되었다. 모의실험을 위해 실제 세계와 유사한 가상세계를 컴퓨터 속에 구현하고자 한 노력은 객체지향 이론을 탄생시켰다.

객체지향 이론의 기본 개념은 실제 세계는 사물(객체)로 이루어져 있으며, 발생하는 모든 사건들은 사물 간의 상호작용이다. 자바가 1995년에 발표되고 1990년대 인터넷의 발전과 함께 크게 유행하면서 객체지향 언어는 이제 프로그래밍 언어의 주류로 자리 잡았다.

 

객체지향 언어

기존의 프로그래밍 언어에 몇 가지 새로운 규칙을 추가한 보다 발전된 형태의 것이다. 객체지향 언어의 특징은 다음과 같다.

1. 코드의 재사용성이 높다.
	새로운 코드를 작성할 때 기존의 코드를 이용하여 쉽게 작성할 수 있다.
2. 코드의 관리가 용이하다.
	코드간의 관계를 이용해서 적은 노력으로 쉽게 코드를 변경할 수 있다.
3. 신뢰성이 높은 프로그래밍을 가능하게 한다.
	제어자와 메서드를 이용해서 데이터를 보호하고 올바른 값을 유지하도록 하며,
    코드의 중복을 제거하여 코드의 불일치로 인한 오동작을 방지할 수 있다.

객체지향언어의 가장 큰 장점은 코드의 재사용성이 높고 유지보수가 용이하다는 것이다. 

객체지향 개념을 학습할 때 재사용성과 유지보수 그리고 중복된 코드의 제거, 이 세 가지 관점에서 보면 보다 쉽게 이해할 수 있다. 

 

 

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

 

 

 

 

2차원 이상의 배열, 다차원 배열도 선언해서 사용할 수 있다.

 

2차원 배열의 선언과 인덱스

 

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

3차원 이상의 고차원 배열의 선언은 대괄호[]의 개수를 차원 수만큼 추가해 주면 된다.

배열을 생성하면, 요소에는 배열 요소 타입의 기본값이 자동적으로 저장된다.

 

2차원 배열의 index

2차원 배열은 행(row)와 열(column)으로 구성되어 있기 때문에 index도 행과 열에 각각 하나씩 존재한다.

'행 index'의 범위는 0~행의 길이-1이고, 열의 길이도 마찬가지로 0~열의 길이-1이다.

각 요소에 접근하는 방법은 배열 이름[행 index][열 index]이다.

 

2차원 배열도 중괄호{}를 사용해서 생성과 초기화를 동시에 할 수 있다. 1차원과 다른 점은 중괄호{}를 한번 더 쓴다는 것이다.

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

각 좌표별 값과 총합을 나타내는 코드이다.

향상된 for문으로 배열의 각 요소에 저장된 값들을 순차적으로 읽어올 수 있지만, 배열에 저장된 값을 변경할 수는 없다.

 

 

가변 배열

2차원 이상의 다차원 배열을 생성할 때 전체 배열 차수 중 마지막 차수의 길이를 지정하지 않고, 추후에 각기 다른길이의 배열을 생성함으로써 고정된 형태가 아닌 보다 유동적인 가변배열을 구성할 수 있다.

int[][] score = new int[5][];
score[0] = new int[4];
score[1] = new int[3];
score[2] = new int[2];
score[3] = new int[2];
score[4] = new int[3];

score.length의 값은5지만 score[0].length는 4, score[1].length는 3으로 서로 다르다.

가변배열도 중괄호{}를 이용해서 생성과 초기화를 동시에 하는것이 가능하다.

 

다차원 배열의 활용

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

행열의 곱셈을 배열로 표현한 코드이다.

4-1 다음의 문장들을 조건식으로 표현하라.

1. int형 변수 x가 10보다 크고 20보다 작을 때 true인 조건식
2. char형 변수 ch가 공백이나 탭이 아닐 때 true인 조건식
3. char형 변수 ch가 ‘x' 또는 ’X'일 때 true인 조건식
4. char형 변수 ch가 숫자(‘0’~‘9’)일 때 true인 조건식
5. char형 변수 ch가 영문자(대문자 또는 소문자)일 때 true인 조건식
6. int형 변수 year가 400으로 나눠떨어지거나 또는 4로 나눠떨어지고 100으로 나눠떨어지지
않을 때 true인 조건식
7. boolean형 변수 powerOn가 false일 때 true인 조건식
8. 문자열 참조변수 str이 “yes”일 때 true인 조건식
		if (x > 10 && x < 20);
		if (ch == ' ' || ch=='	');
		if (ch=='x'||ch=='X');
		if (0<=ch&&ch<=9);
		if ('a'<=ch&&ch<='z'||'A'<=ch&&ch<='Z');
		if (year%400==0||(year%4==0&&year!=0));
		if (powerOn == false);
		if (str=="yes");

 

 

 

4-2 1부터 20까지의 정수 중에서 2 또는 3의 배수가 아닌 수의 총합을 구하시오.

public class JavaExercise4_2 {
	public static void main(String[] args) {
		int i = 0;
		int sum = 0;

		for (i = 1; i <= 20; i++) {
			if (i % 2 != 0 && i % 3 != 0) {
				sum += i;
			}
		};
		System.out.println(sum);
	}
}
73

 

 

 

4-3 1+(1+2)+(1+2+3)+(1+2+3+4)+...+(1+2+3+...+10)의 결과를 계산하시오.

public class JavaExercise4_3 {
	public static void main(String[] args) {
		int i=1;
		int a=0;
		int s=0;
		
		for(i=1;i<=10;i++) {
			a=a+i;
			s=s+a;			
		}
		System.out.println(s);
	}
}
220

 

 

 

4-4 1+(-2)+3+(-4)+... 과 같은 식으로 계속 더해나갔을 때, 몇까지 더해야 총합이 100 이상이 되는지 구하시오.

public class JavaExercise4_4 {
	public static void main(String[] args) {
		int sum = 0; // 총합을 저장할 변수
		int s = 1; // 값의 부호를 바꿔주는데 사용할 변수
		int num = 0;
		// 조건식의 값이 true이므로 무한반복문이 된다.
		for (int i = 1; sum < 100; i++) {
			s = -s;
			num = i * s;
			sum += num;
		}
		System.out.printf("num= %d%n",num-1);
		System.out.printf("sum= %d", sum);
	} // main
}
num= 199
sum= 100

 

 

4-5 다음의 for문을 while문으로 변경하시오.

	public static void main(String[] args) {
		for (int i = 0; i <= 10; i++) {
			for (int j = 0; j <= i; j++)
				System.out.print("*");
			System.out.println();
		}
	} // end of main
} // end of class
public class JavaExercise4_5 {
	public static void main(String[] args) {
		int i = 0;

		while (i <= 10) {
			int j = 0;
			while (j <= i) {
					System.out.printf("*");
					j++;
					}

			System.out.println();
			i++;
				}
		} // end of main
	}  // end of class

 

 

 

4-6 두 개의 주사위를 던졌을 때, 눈의 합이 6이 되는 모든 경우의 수를 출력하는 프로그램을 작성하시오.

public class JavaExercise4_6 {
	public static void main(String[] args) {
		int i=0;
		int j=0;
		for(i=1;i<6;i++) {
			j=6-i;
			System.out.printf("[%d, %d]",i ,j);
			System.out.println();
		}
	}
}
[1, 5]
[2, 4]
[3, 3]
[4, 2]
[5, 1]

 

 

4-7 Math.random()을 이용해서 1부터 6사이의 임의의 정수를 변수 value에 저장하는 코드를 완성하라. (1)에 알맞은 코드를 넣으시오.

public class JavaExercise4_7 {
	public static void main(String[] args) {
		int value = ( /* (1) */ );
		System.out.println("value:"+value);
		}
}
(int)Math.random()*6+1
value:1

 

 

 

4-8 방정식 2x+4y=10의 모든 해를 구하시오. 단, x와 y는 정수이고 각각의 범위는 0 <=x <=10, 0 <=y <=10이다.

public class JavaExercise4_8 {
	public static void main(String[] args) {
		int x = 0;
		int y = 2;
		for (x = 1; x <= 10; x++) {
			for (y = 0; y <= 10; y++) {
				if (2 * x + 4 * y == 10) {
					System.out.println("x=" + x + ", y=" + y);
				}
			}
		}
	}
}
x=1, y=2
x=3, y=1
x=5, y=0

 

4-9 숫자로 이루어진 문자열 str이 있을 때, 각 자리의 합을 더한 결과를 출력하는 코드를 완성하라. 만일 문자열이 "12345"라면, ‘1+2+3+4+5’의 결과인 15를 출력이 출력되어야 한다. (1)에 알맞은 코드를 넣으시오.
[Hint] String클래스의 charAt(int i)을 사용

public class JavaExercise4_9 {
	public static void main(String[] args) {
		String str = "12345";
		int sum = 0;
		for (int i = 0; i < str.length(); i++) {
		/*
		(1) 알맞은 코드를 넣어 완성하시오.
		*/
		}
		System.out.println("sum=" + sum);
	}
}
public class JavaExercise4_9 {
	public static void main(String[] args) {
		String str = "12345";
		int sum = 0;
		for (int i = 0; i < str.length(); i++) {
			sum += str.charAt(i)-'0';
		}
		System.out.println("sum=" + sum);
	}
}
sum=15

 

 

 

4-10 int타입의 변수 num 이 있을 때, 각 자리의 합을 더한 결과를 출력하는 코드를 완성하라. 만일 변수 num의 값이 12345라면, ‘1+2+3+4+5’의 결과인 15를 출력하라. (1)에 알맞은 코드를 넣으시오.
[주의] 문자열로 변환하지 말고 숫자로만 처리해야 한다.

public class JavaExercise4_10 {
	public static void main(String[] args) {
		int num = 12345;
		int sum = 0;
		/*
			(1) 알맞은 코드를 넣어 완성하시오.
		*/
		System.out.println("sum=" + sum);
	}
}
public class JavaExercise4_10 {
	public static void main(String[] args) {
		int num = 12345;
		int sum = 0;
		for (int i = 0; i<=5; i++) {
			sum = num % 10 + sum;
			num = (num-num%10)/10;
		}
		System.out.println("sum=" + sum);
	}
}

 

 

 

4-11 피보나치(Fibonnaci) 수열(數列)은 앞을 두 수를 더해서 다음 수를 만들어 나가는 수열이다. 예를 들어 앞의 두 수가 1과 1이라면 그다음 수는 2가 되고 그 다음 수는 1과 2를 더해서 3이 되어서 1,1,2,3,5,8,13,21,... 과 같은 식으로 진행된다. 1과 1부터 시작하는 피보나치수열의 10번째 수는 무엇인지 계산하는 프로그램을 완성하시오.

public class JavaExercise4_11 {
	public static void main(String[] args) {
		// Fibonnaci 수열의 시작의 첫 두 숫자를 1, 1로 한다.
		int num1 = 1;
		int num2 = 1;
		int num3 = 0; // 세번째 값
		System.out.print(num1 + "," + num2);

		for (int i = 0; i < 8; i++) {
		/*
			(1) 알맞은 코드를 넣어 완성하시오.
		*/
		}
	}// end of main
}// end of class
public class JavaExercise4_11 {
	public static void main(String[] args) {
		// Fibonnaci 수열의 시작의 첫 두 숫자를 1, 1로 한다.
		int num1 = 1;
		int num2 = 1;
		int num3 = 0; // 세번째 값
		System.out.print(num1 + "," + num2);

		for (int i = 0; i < 8; i++) {

			num3 = num1 +num2;
			num1 = num2;
			num2 = num3;
			System.out.print(","+num3);
		}
	}// end of main
}// end of class

 

4-12 구구단의 일부분을 다음과 같이 출력하시오.

public class JavaExercise4_12 {
	public static void main(String[] args) {
		for (int i = 1; i <= 9; i++) {
			for (int j = 1; j <= 3; j++) {
				int x = j + 1 + (i - 1) / 3 * 3;
				int y = i % 3 == 0 ? 3 : i % 3;
				if (x > 9) // 9단까지만 출력한다. 이 코드가 없으면 10단까지 출력된다.
					break;
				System.out.print(x + "*" + y + "=" + x * y + "\t"); // println이 아님에 주의
			}
			System.out.println();
			if (i % 3 == 0)
				System.out.println(); //
		}
	} // end of main
} // end of class
public class JavaExercise4_12_1 {
	public static void main(String[] args) {
		int n = 2;
		for (int j = 1; j <= 3; j++) {
			for (int i = 1; i <= 3; i++) {
				System.out.printf("%dx%d=%d\t", n, i, n * i);
				System.out.printf("%dx%d=%d\t", n + 1, i, (n + 1) * i);
				if(n!=8) 
				System.out.printf("%dx%d=%d", n + 2, i, (n + 2) * i);
				System.out.println();
			}
			n +=3;
			System.out.println();
		}
	}
}
2x1=2	3x1=3	4x1=4
2x2=4	3x2=6	4x2=8
2x3=6	3x3=9	4x3=12

5x1=5	6x1=6	7x1=7
5x2=10	6x2=12	7x2=14
5x3=15	6x3=18	7x3=21

8x1=8	9x1=9	
8x2=16	9x2=18	
8x3=24	9x3=27

 

 

4-13 다음은 주어진 문자열(value)이 숫자인지를 판별하는 프로그램이다. (1)에 알맞은 코드를 넣어서 프로그램을 완성하시오.

public class JavaExercise4_13 {
	public static void main(String[] args) {
		String value = "12o34";
		char ch = ' ';
		boolean isNumber = true;
		// 반복문과 charAt(int i)를 이용해서 문자열의 문자를
		// 하나씩 읽어서 검사한다.
		for (int i = 0; i < value.length(); i++) {
			/*
				(1) 알맞은 코드를 넣어 완성하시오.
			*/
			}
		}
		if (isNumber) {
			System.out.println(value + "는 숫자입니다.");
		} else {
			System.out.println(value + "는 숫자가 아닙니다.");
		}
	} // end of main
} // end of class
public class JavaExercise4_13 {
	public static void main(String[] args) {
		String value = "12o34";
		char ch = ' ';
		boolean isNumber = true;
		// 반복문과 charAt(int i)를 이용해서 문자열의 문자를
		// 하나씩 읽어서 검사한다.
		for (int i = 0; i < value.length(); i++) {
			ch = value.charAt(i);
			if ('0' >= ch || ch >= '9'|| isNumber==false) {
				isNumber = false;
				break;
			}
		}
		if (isNumber) {
			System.out.println(value + "는 숫자입니다.");
		} else {
			System.out.println(value + "는 숫자가 아닙니다.");
		}
	} // end of main
} // end of class
12o34는 숫자가 아닙니다.

 

 

4-14 다음은 숫자 맞추기 게임을 작성한 것이다. 1과 100 사이의 값을 반복적으로 입력해서 컴퓨터가 생각한 값을 맞추면 게임이 끝난다. 사용자가 값을 입력하면, 컴퓨터는 자신이 생각한 값과 비교해서 결과를 알려준다. 사용자가 컴퓨터가 생각한 숫자를 맞추면 게임이 끝나고 몇 번 만에 숫자를 맞췄는지 알려준다. (1)~(2)에 알맞은 코드를 넣어 프로그램을 완성하시오.

public class JavaExercise4_14 {
	public static void main(String[] args) {
		// 1~100사이의 임의의 값을 얻어서 answer에 저장한다.
		int answer =  /* (1) */;
		int input = 0; // 사용자입력을 저장할 공간
		int count = 0; // 시도횟수를 세기위한 변수
		// 화면으로 부터 사용자입력을 받기 위해서 Scanner클래스 사용
		java.util.Scanner s = new java.util.Scanner(System.in);
		/*
			(2) 알맞은 코드를 넣어 완성하시오.
		*/	
		}
		while (true); // 무한반복문
	} // end of main
} // end of class HighLow
public class JavaExercise4_14 {
	public static void main(String[] args) {
		// 1~100사이의 임의의 값을 얻어서 answer에 저장한다.
		int answer = (int) (Math.random() * 100) + 1;
		int input = 0; // 사용자입력을 저장할 공간
		int count = 0; // 시도횟수를 세기위한 변수
		// 화면으로 부터 사용자입력을 받기 위해서 Scanner클래스 사용
		java.util.Scanner s = new java.util.Scanner(System.in);
		do {
			count++;
			System.out.print("1과 100사이의 값을 입력하세요 :");
			input = s.nextInt(); // 입력받은 값을 변수 input에 저장한다.
			if (answer > input) {
				System.out.println("더 큰 수를 입력하세요.");
			} else if (answer < input) {
				System.out.println("더 작은 수를 입력하세요.");
			} else {
				System.out.println("맞췄습니다.");
				System.out.println("시도횟수는 " + count + "번입니다.");
				break;
				// do-while문을 벗어난다
				
			}
		}
		while (true); // 무한반복문
	} // end of main
} // end of class HighLow
1과 100사이의 값을 입력하세요 :50
더 작은 수를 입력하세요.
1과 100사이의 값을 입력하세요 :25
더 큰 수를 입력하세요.
1과 100사이의 값을 입력하세요 :37
더 작은 수를 입력하세요.
1과 100사이의 값을 입력하세요 :31
맞췄습니다.
시도횟수는 4번입니다.

 

 

4-15 다음은 회 문수를 구하는 프로그램이다. 회 문수(palindrome)란, 숫자를 거꾸로 읽어도 앞으로 읽는 것과 같은 수를 말한다. 예를 들면 ‘12321’이나 ‘13531’ 같은 수를 말한다. (1)에 알맞은 코드를 넣어서 프로그램을 완성하시오.
[Hint] 나머지 연산자를 이용하시오.

public class JavaExercise4_15 {
	public static void main(String[] args) {
		int number = 12321;
		int tmp = number;
		int result = 0; // 변수 number를 거꾸로 변환해서 담을 변수
		
		while (tmp != 0) {
		/*
			(1) 알맞은 코드를 넣어 완성하시오.
		*/
		}
		if (number == result)
			System.out.println(number + "는 회문수 입니다.");
		else
			System.out.println(number + "는 회문수가 아닙니다.");
	} // main
}
public class JavaExercise4_15 {
	public static void main(String[] args) {
		int number = 12321;
		int tmp = number;
		int result = 0; // 변수 number를 거꾸로 변환해서 담을 변수
		
		while (tmp != 0) {
			result = result * 10 + tmp % 10; // 기존 결과에 10을 곱해서 더한다.
			tmp /= 10;
		}
		if (number == result)
			System.out.println(number + "는 회문수 입니다.");
		else
			System.out.println(number + "는 회문수가 아닙니다.");
	} // main
}
12321는 회문수 입니다.

배열의 길이 변경하기

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

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

배열의 길이를 변경하는 방법:
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

+ Recent posts