public class Car{
	
	String carName; //전역변수 (class영역에서 선언했기 때문에 전체적으로 사용할 수 있는 변수)
	String carColor;
	String maker;
	int speed;

	public Car() { //기본 생성자 생성
		//carName = "아반떼";
		//carColor = "흰색";
		//maker = "현대";
		this ("아반떼", "흰색", "현대");
		//speed = 10;
		
	}
	
	// carName만 외부에서 받은 값으로 하고 싶다면?
	public Car(String carName) {  // 왜 cn이 아닌 carName으로 했을 때, null값이 나오는가? 전역변수의 carName은 class영역에 있고, 지역변수의 carName은 메소드 영역에 있기 때문에 같은 이름이 지정가능하다. 지역변수가 전역변수보다 먼저 적용되기 때문에 
		//this.carName = carName; //.을 찍어 새로운 객체가 형성되기 때문에 자기 자신을 참조하기 위해서는 this를 붙여야 한다. 지역변수와 전역변수가 같을 경우 반드시 this를 명시해주어야 한다.
		//carColor = "흰색"; //앞에 this가 생략되어 있음
		//maker = "현대";
		this (carName, "흰색", "현대");
	}

	// carName, carColor만 외부에서 받은 값으로 하고 싶다면?
	public Car(String carName, String carColor) { //타입이나 개수가 달라야 함!! 그냥 String cn하면 x 컴퓨터는 cn,cc를 인식하는 것이 아니라 같은 String으로 인식하기 때문!!
		//this.carName = carName;
		//this.carColor = carColor;
		//maker = "현대";
		this(carName,carColor,"현대");

	}
	
	// 초기화 내용(중복 코드)을 몰아서 작성한 생성자 this()
	public Car(String carName, String carColor, String maker) { //타입이나 개수가 달라야 함!! 그냥 String cn하면 x 컴퓨터는 cn,cc를 인식하는 것이 아니라 같은 String으로 인식하기 때문!!
		this.carName = carName;
		this.carColor = carColor;
		this.maker = maker;

	}

	void speedUp() { //접근제어자 생략 가능, ()안 인자값 생략 가능
		speed += 10;

	}

	int speedUp(int speed) { 
		this.speed += speed;
		return this.speed;

	}

	void speedDown() {
		speed -= 10;
		if(speed < 0)
			//speed = 0;
			stop(); //그냥 stop을 호출하면 됨
	}

	void stop() {
		speed = 0;
	}

}
public class CarUser{
	public static void main(String[] args) {
		Car car1 = new Car();
		System.out.println("1. " + car1.maker + "에서 만든 " + car1.carColor + " " + car1.carName + "입니다. ");
		
		car1.carName = "쏘나타";
		car1.carColor = "남색";
		car1.maker = "현대";
		System.out.println("2. " + car1.maker + "에서 만든 " + car1.carColor + " " + car1.carName + "입니다. ");

		System.out.println("속도를 5회증가!!!");
		for (int i=0;i<5;i++)
			car1.speedUp();
		System.out.println("car1의 속도 : " + car1.speed);

		System.out.println("속도를 150회증가!!!");
		int s = car1.speedUp(150);
		System.out.println("car1의 속도 : " + s);
		

		Car car2 = new Car("제네시스"); //내가 원하는 이름을 지정해서 넣을 수 있다
		System.out.println("3. " + car2.maker + "에서 만든 " + car2.carColor + " " + car2.carName + "입니다. ");

		Car car3 = new Car("그랜저", "검정색"); 
		System.out.println("4. " + car3.maker + "에서 만든 " + car3.carColor + " " + car3.carName + "입니다. ");

		//기아에서 만든 빨간색 K5입니다.

		Car car4 = new Car("K5", "빨간색", "기아"); 
		System.out.println("5. " + car4.maker + "에서 만든 " + car4.carColor + " " + car4.carName + "입니다. ");
	}
}
---------- run ----------
1. 현대에서 만든 흰색 아반떼입니다. 
2. 현대에서 만든 남색 쏘나타입니다. 
속도를 5회증가!!!
car1의 속도 : 50
속도를 150회증가!!!
car1의 속도 : 200
3. 현대에서 만든 흰색 제네시스입니다. 
4. 현대에서 만든 검정색 그랜저입니다. 
5. 기아에서 만든 빨간색 K5입니다. 

 

(1) Null : 변수(스택 영역)가 참조하는 객체(힙 영역)가 없을 경우 초기값으로 사용

: 참조 타입의 변수에만 저장 가능 (기본타입은 사용 x)

: 값이 없는 변수는 stack 영역에 생성되지 않지만, null로 초기화된 참조 변수는 stack 영역에 생성

String str = null;
char c = str.charAt(0); //NullPointerException

 

여기서 null이란 str이란 String 변수가 선언만 되어 있고, 참조하고 있는 주소값이 없다는 것

즉, 존재하지 않는 객체를 가리킬 때 발생한다.

null을 사용하는 이유는? 자원을 해제하기 위해서 주로 사용한다. 추후에 사용되지 않으면 자동 소멸됨.

 

(2) NullPointerException : 가장 자주 발생하는 에러, 가장 잡기 쉬우면서 어려운 에러

 

- 발생 원인 : 참조 변수가 null값을 가지고 있는데 객체의 필드나 메소드를 사용하려고 했을 때 발생

(에러가 발생된 곳에서 객체를 참조하지 않은 상태로 참조 타입 변수를 사용하고 있음)

- 해결법 : 변수 추적, 객체를 참조하도록 수정

 

(3) String : 문자열을 저장하는 클래스 타입

Q.동일한 문자열 리터럴을 String에 대입하고자 한다면? 힙 영역의 같은 String 객체를 공유 (객체 하나만 생성됨)

Q. 동일한 문자열 리터럴을 같은 String이 아닌 다른 String 객체에 대입하고자 한다면?

new 연산자를 이용한 String 객체 생성 : 힙 영역에 새로운 String 객체를 생성 >> 번지를 리턴

 

(4) 참조 변수의 ==, != 연산

- 동일한 객체를 참조하는지 서로 다른 객체를 참조하는지 조사하는 것

 

(5) 문자열 비교시 주의사항 ***

주로 Sring은 동일한 객체를 참조하는지를 비교하지 않고, 객체 안 문자열이 동일한지를 비교한다.

ex) String name1 = "홍길동";

String name2 = "홍길동";

String name3 = new String ("홍길동");

 

>> name1.equals(name3) //true (문자열 동일 o, 객체 동일x)

 

(6) 배열

- 같은 타입의 데이터를 연속된 공간에 저장하는 자료구조

- 각 데이터의 저장 위치는 인덱스(번호)를 부여해서 접근할 수 있다.

 

Q. 배열을 왜 사용하는가?

>> 변수의 수가 많을 경우, 연산을 하기 어렵기 때문에 쉽게 연산을 하기 위해서

>> 같은 타입의 변수들을 효율적으로 관리하기 위해서 (반복문 사용)

>> 코드 절감하기 위해서

 

index

85

0

96

1

74

2

76

3

.....

....

88

44

 

- 배열이름[인덱스번호] (*인덱스 번호는 0번부터 시작되고, 자동으로 생성된다.)

( 주로 배열은 for문과 함께 사용되어 최댓값, 최솟값, 평균, 총합 등을 구한다.)

ex) score[2] = 79; // index 2번인 74점을 79점으로 변경하여 대입.

ex) 0~44번까지의 총학점과 평균을 구하라.

int sum = 0;

for (i=0; i<45; ,i++) {

sum += score[i];

}

int avg = sum / 45;

 

선언) 타입[ ] 변수;

int[ ] intArray;

double[ ] doubleArray;

String[ ] strArray;

 

사용)

1. 변수 선언과 동시에 값 대입

데이터 타입[ ] 변수 = {값1,값2.........};

String[ ] names = {"홍길동", "임꺽정"};

public class ArrayCreateByValueListExample{
	public static void main(String[] args) {
		int[] scores = {95,80,99}; // scores 배열 변수는 stack 영역에 생성, {95,80,99} 배열 객체는 heap 영역에 생성

		System.out.println("scores[0]:" + scores[0] ); //index번호 0부터 자동 생성됨
		System.out.println("scores[1]:" + scores[1] );
		System.out.println("scores[2]:" + scores[2] );

		int sum = 0;
		for (int i=0;i<3 ;i++ ){ //0~2 
			sum += scores[i]; //배열에 저장되어 있는 값들을 더하라 
		}
		System.out.println("총합 :" + sum);

		double avg = (double) sum/ 3;
		System.out.println("평균 : " + avg);
	}
}
---------- run ----------
scores[0]:95
scores[1]:80
scores[2]:99
총합 :274
평균 : 91.33333333333333

2. 변수 선언 후 값 대입

데이터 타입 [ ] 변수;

변수 = new 타입 [ ] {값1, 값2.....};

String[ ] names = null;

names = new String [ ] {"홍길동","임꺽정"};

 

* 배열은 참조 변수이기 때문에 null로 초기화가 가능하다.

(but, null값을 가진 상태에서 항목에 접근하기 위해 "변수[인덱스]"를 하면 NullPointerException 발생)

 

Q. 이미 선언한 배열을 매개변수로 가지는 메소드를 호출하고 싶다면?

>> int add (int[] scores) {......} --- int 배열의 값을 모두 더해서 return하는 메소드

ex)

int result = add({95,80,99}); //컴파일 에러 발생

int result = add(new int[] {95,80,99} );

public class ArrayCreateByValueListExample2 {
	public static void main(String[] args) {
		int[] scores;
		//scores = {83,90,87}; //컴파일 에러 
		scores = new int[] {83,90,97};//배열변수 선언 후 값 대입을 할 떄는 new 붙이기
		
		int sum1 = 0;
		for (int i=0;i<3;i++){
			sum1 += scores[i];
		}
		System.out.println("총합 : " + sum1);

		int sum2 = add(new int[] {83,90,97});
		System.out.println("총합 : " + sum2);

	}

	public static int add(int[] scores) { //add라는 메소드 사용
		int sum = 0;
		for (int i=0;i<3;i++){
			sum += scores[i];
		}
		return sum;
	}
---------- run ----------
총합 : 270
총합 : 270

3. new 연산자로 배열 생성 : 배열 생성시 값을 대입하지 않고, 추후에 값들을 대입하고 싶을 경우

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

int[] socres = new int[5]; //5개의 값

 

데이터 타입

초기값

기본타입(정수)

new byte[]

new char[]

new short[]

new int[]

new long[]

0

공백

0

0

0

기본타입(실수)

new float[]

new double[]

0.0

0.0

기본타입(논리)

new boolean[]

false

참조타입

클래스[]

인터페이스[]

null

null

public class ArrayCreateByNewExample {
	public static void main(String[] args) {
		int [] arr1 = new int[3]; //배열생성
		for (int i=0;i<3 ;i++ ){
			System.out.println("arr1[" + i + "] : " + arr1[i]);//초기값 알아보기 위해서
		}
		System.out.println(); // 한 줄 생성

		arr1[0] = 10; // 0번 인덱스에 10이라는 값 저장
		arr1[1] = 20;
		arr1[2] = 30;
		for (int i=0;i<3 ;i++ ){
			System.out.println("arr1[" + i + "] : " + arr1[i]);
		}
		System.out.println();

		double[] arr2 = new double[3];
		for (int i=0;i<3 ;i++ ){
			System.out.println("arr2[" + i + "] : " + arr2[i]);//초기값 알아보기 위해서
		}
		System.out.println();

		arr2[0] = 0.1;
		arr2[1] = 0.2;
		arr2[2] = 0.3;
		for (int i=0;i<3 ;i++ ){
			System.out.println("arr2[" + i + "] : " + arr2[i]);
		}
		System.out.println();

		String[] arr3 = new String[3];
		for (int i=0;i<3 ;i++ ){
			System.out.println("arr3[" + i + "] : " + arr3[i]);//초기값 알아보기 위해서
		}
		System.out.println();

		arr3[0] = "1월";
		arr3[1] = "2월";
		arr3[2] = "3월";
		for (int i=0;i<3 ;i++ ){
			System.out.println("arr3[" + i + "] : " + arr3[i]);
		}
	}
}
---------- run ----------
arr1[0] : 0
arr1[1] : 0
arr1[2] : 0

arr1[0] : 10
arr1[1] : 20
arr1[2] : 30

arr2[0] : 0.0
arr2[1] : 0.0
arr2[2] : 0.0

arr2[0] : 0.1
arr2[1] : 0.2
arr2[2] : 0.3

arr3[0] : null
arr3[1] : null
arr3[2] : null

arr3[0] : 1월
arr3[1] : 2월
arr3[2] : 3월

 

(7)

java : 객체 지향 프로그래밍

c : 절차 지향 프로그래밍

객체들은 서로 다른 객체들과 관계를 맺고 있다.

(위에서부터 순서대로 이루어짐)

- 관계 종류

1. 집합 관계 : 자동차 -- 엔진, 타이어, 핸들

2. 사용 관계 : 사람 --> 자동차

3. 상속 관계 : 자동차 --> 기계

 

 

 

** 붕어빵 생각하기

1. 붕어빵 틀 : 클래스

2. 팥, 초코, 딸기 붕어빵 : 각각의 객체

3. 클래스 (속성, 기능) 두개로 나뉜다.

 

** object (참조형(Reference) DataType)

- class (Object)

- array

 

* 메소드(동작)를 호출하고 결과를 리턴한다.

 

(1) class : 객체(object)를 생성하기 위한 틀, 설계도

: 속성(field), 기능(method)으로 이루어져 있음

=(특징,명사) =(동작,동사)

 

** 클래스 용도

1. 라이브러리 API : 자체적으로 실행X, 다른 클래스에서 이용할 목적으로 만든 클래스

2. 실행용 : main() 메소드를 가지고 있는 클래스로 실행할 목적으로 만든 클래스

(주로, 1개의 어플리케이션 = 1개의 실행클래스로 충분 + 여러개의 라이브러리 클래스)

 

형식)

public class ClassName {

 

//Field : 객체의 데이터가 저장되는 곳

int FieldName;

String FieldName;

int FieldName = 초기값;

1. 객체 내부 사용 : 생성자 or 메소드 영역에서 바로 필드이름으로 사용 ex) speed = 10;

2. 객체 외부 사용 : Car car1 = new Car(); 새로운 객체 생성 후 car1.speed = 10; 사용

 

//Constructor : 객체 생성시 초기화 역할

ClassName() {.............};

Car(String model, String color, int maxSpeed) {........}

사용:Car myCar = new Car("그랜저","검정",300);

 

//Method : 객체 동작에 해당하는 실행 블록

접근제어자 ReturnType methodName([args]) { //[ ]:생략가능,return값이 없을 때는

ReturnType에 void 입력

기능 구현

[return 값;] // return값이 있는 경우 반드시 return문을 사용해서 리턴값을 지정해야 한다.!!

}

void methodName() {..................}; * 메소드 안에 있는 변수는 접근제어자 생략 가능

}

(2) 메소드 (Method) : 서로 연관된 코드를 정리정돈해주는 역할!!!



> 리턴타입 : 메소드가 실행 후 리턴하는 값의 타입(ex) 메소드 실행 후 int값, String 문자열이 리턴해서 나옴)

: 리턴값이 있을 수도 있고, 없을 수도 있다.

: 메소드의 실행을 중지하고 리턴값을 지정하는 역할 (return문 뒤에 실행문이 올 수 x)

선언)

void powerOn() {} // void 리턴 값이 없을 때 사용, 실행만 하고 끝남

double divide (int x, int y) {} // double : 나눗셈 결과를 리턴해야 되기 때문에 리턴타입이 있고, 실행할 때 정수 x,y값이 필요하다는 뜻이다.

 

호출)

powerOn(); // 리턴 값이 없기 때문에 메소드 이름만 ~

double result = divide (10,20); // 리턴 타입이 double이기 때문에 double로 받고, x,y에 해당하는 값도 명시해야 함!!리턴값을 저장할 변수가 필요하기 때문에 double로 잡기!!

* 리턴 타입이 있다고 해서 반드시 리턴값을 변수에 저장할 필요는 없다. 리턴값이 중요하지 않고, 메소드 실행이 중요할 경우, 변수 선언 없이 divide(10,20); 메소드 호출하기

 

public class Calculator {
	void powerOn() {
		System.out.println("전원을 켭니다.");
	}

	int plus(int x, int y){ //int : 리턴타입, plus : 메소드
		int result = x+y; // 기능구현
		return result; // result값을 리턴하라는 뜻
	}

	double divide(int x, int y){
		double result = (double)x/(double)y;
		return result;
	}
}
public class CalculatorUser {
	public static void main(String[] args) {
		Calculator cal = new Calculator();
		cal.powerOn();

		int result1 = cal.plus(10,20);// x+y를 한 result값이 리턴되어 result1에 저장
		System.out.println("result1 : " + result1);

		byte x = 10;
		byte y = 4;
		double result2 = cal.divide(x,y); //리턴타입이 double이기 때문에 double로 받아야 함
		System.out.println("result2 : " + result2);

	}
}
---------- run ----------
전원을 켭니다.
result1 : 30
result2 : 2.5

 

> 매개변수 : 메소드가 실행할 때 필요한 데이터를 외부로부터 받기 위해 사용

매개 변수를 모를 경우?

(방법1) ---- 배열을 매개 변수로 할 경우 {} 중괄호 사용해야 함!!

int sum1(int[] values) {};

----------------------------

int[] values = {1,2,3};

int result = sum1(values);

or

int result = sum1(new int[] {1,2,3,4,5});

 

(방법2)

int sum2(int... values) {} --- 그냥 1,2,3 값을 대입해도 알아서 배열로 인식함!!

-----------------------------

int result = sum2(1,2,3);

or

int result = sum2(1,2,3,4,5);

public class Computer {
	int sum1(int[] values){
		int sum = 0;
		for (int i=0;i<values.length ;i++ ){
			sum += values[i];
		}
		return sum;
	}

	int sum2(int...values){
		int sum = 0;
		for (int i=0;i<values.length ;i++ ){
			sum += values[i];
		}
		return sum;
	}
}
public class ComputerUser {
	public static void main(String[] args) {
		Computer myCom = new Computer();

		int[] values1 = {1,2,3}; //미리 배열을 만들어 놓는 경우
		int result1 = myCom.sum1(values1);
		System.out.println("result1: " + result1);

		int result2 = myCom.sum1(new int[] {1,2,3}); //메소드 호출 시 직접 매개 값으로 주는 경우
		System.out.println("result2: " + result2);

		int result3 = myCom.sum2(1,2,3);
		System.out.println("result3: " + result3);

		int result4 = myCom.sum2(1,2,3,4,5);
		System.out.println("result4: " + result4);

	}
}

(3) 생성자(Constructor)

* 라이브러리 클래스에서 생성자를 생성하고, 실행 클래스에서 new연산자로 생성자를 호출해 객체를 생성

a. 객체 생성시 최초로 한번만 호출이 되는 메소드의 일종

반드시 new 연산자와 함께 사용!!!! (객체를 생성한 후, 객체 생성 번지를 리턴한다.)

b. 객체의 field값 초기화

c. Class의 이름과 같고 Return Type이 없다.

형식)

접근제어자 ClassName([args]) { // 접근제어자 public class에서 선언을 했다면, 접근제어자 생략 ok~

}

d. 사용자가 생성자를 생략할 경우, default 생성자가 생략되어 있다고 생각하면 ok~

public ClassName() { }

사용자가 생성자를 생성했을 경우, 라이브러리 클래스에서 매개변수를 입력하고, 실행클래스에서 값을 입력해야 함

사용자가 클래스 내부에 하나라도 생성자를 생성했을 경우, default 생성자는 생성되지 않는다.

 

e. 메소드의 overloading ************************

- 클래스 내에 같은 이름의 메소드를 여러 개 선언하는 것

- 외부의 값이 어떤 타입으로 몇 개가 입력될 지 모르기 때문에 메소드도 다양해질 필요가 있을 때

단, 인자값의 개수가 다르거나, 인자값의 타입, 인자값의 순서가 달라야 한다. (리턴타입,인자값의 이름은 상관x)

ex)

public void a() {} :기준

public void a() {} : x

public void a(int x) {} : O

public void a(Sting s) {} : O

public void a(int y) {} : x , int x와 int 타입이 같다

public int a() {} : x

private void a() {} : x

public void a(int x, String s) {} : o

public void a(String s, int x) {} : o //위에랑 순서가 바뀌었다고 보지 말고, 컴퓨터는 첫번째부터 인식한다.

public class Printer{ void printin(int a){ System.out.println(a); } void println(boolean a){ System.out.println(a); } void println(double a){ System.out.println(a); } void println(String a){ System.out.println(a); } }

 

public class Printer{
	
	void printin(int a){
		System.out.println(a);
	}

	void println(boolean a){
		System.out.println(a);
	}

	void println(double a){
		System.out.println(a);
	}

	void println(String a){
		System.out.println(a);
	}	
}
public class PrinterExample {
	public static void main(String[] args) {
		Printer printer = new Printer();

		printer.println(10);
		printer.println(true);
		printer.println(5.7);
		printer.println("홍길동");
	}
}

f. ************

< this : 자기클래스 참조변수 >

-- 생성자의 매개변수와 필드명이 동일할 경우,,

> 관례적으로 매개변수의 값을 필드값으로 설정할 경우 매개변수와 필드명을 동일하게 한다.(n보다는 name으로!)

> 생성자 내부에서는 매개변수가 우선순위를 갖는다.

> 필드임을 명시하기 위해 this.필드명을 사용한다.

ex) public Korean(String name, String ssn) {

name = name; // 필드명 앞에 this.를 쓰지 않으면? 매개변수의 값을 매개변수에 저장하라는 뜻이 된다.

필드명 매개변수

this.name = name; // 따라서, this.의 의미는 외부에서 매개변수로 받은 값을 필드에 저장하라는 뜻이 된다.

}

 

< super : 상위클래스 참조변수>

 

< this() : 자기클래스 생성자 호출 > : 중복 코드 줄이기, 반드시 첫 줄에 와야 함!!

-- 생성자가 오버로딩되면 생성자 간의 중복된 코드가 발생될 수 있다.

-- 초기화 내용이 비슷한 생성자들에서 주로 발생

> 해결방법 : 초기화 내용을 한 생성자에 몰아서 작성한다. (주로 모든 생성자의 내용을 포함할 수 있는 생성자로 함)

: 다른 생성자는 초기화 내용을 작성한 생성자를 this()로 호출한다.

 

< super() : 상위클래스 생성자 호출 >

 

* Car.java:13: error: call to this must be first statement in constructor

-- this(), super()는 생성자의 첫줄에서만 호출이 가능하다.

 

(4) Reference DataType의 사용

a.선언

형식)

접근제어자 참조형DataType(ClassName) 객체명;

ex)

public String carName;

private Car car;

TV tv;

Radio r;

b.생성 : class를 메모리에 할당

형식)

객체명 = new ClassName;

ex)

carName = new String("쏘나타");

car = new Car();

tv = new TV();

r = new Radio();

 

>> a, b를 동시에

접근제어자 객체명 = new ClassName();

public String carName = new String("쏘나타");

private Car car = new Car();

 

c.사용

형식) 객체명.변수 = 값;

객체명.변수 // System.out.println( );에서 주로 사용

객체명.methodName( );

ex)

car.carName;

System.out.println(car.carName);

car.speedUp( );

 

(5) 메모리 사용 영역 *

JVM은 OS에서 할당받은 메모리 영역을 3 영역으로 구분한다.

Method

클래스 생성

Heap

(동적할당)

car1

carName

carColor

maker

speed

---------------

car2

carName

carColor

maker

speed

.

.

.

- class타입인 string("문자열") 등의 객체가 Heap 영역에 생성,

배열 생성

- 사용되지 않는 객체는 GC가 자동 제거

Stack

car1 car2 car3

변수 생성

기본타입 변수 : 값을 직접 저장

참조타입 변수 : Heap영역에 생성된 주소값이 Stack에 저장 (Heap 영역을 참조한다)

 

<순서>

1.Car라는 객체를 만들 것이다.

2.car1 = new Car;

3.Car생성

4.car1.carName : ' . ' 의 의미는 ' in ' (Heap에서 car1의 주소값을 가져온다.)

 

ex)

class : 자동차 Car

 

field : 차이름 carName

차색상 carColor

제조사 maker

속도 speed

 

method : 가속 speedUp >> 한 번 호출시 속도가 10씩 증가

감속 speedDown >> 감소

정지 stop >> 속도를 0으로

public class Car{
	
	String carName; //전역변수 (class영역에서 선언했기 때문에 전체적으로 사용할 수 있는 변수)
	String carColor;
	String maker;
	int speed;

     //생성자 default 값으로 생략되어 있음.

	void speedUp() { //접근제어자 생략 가능, ()안 인자값 생략 가능
		speed += 10; // 필드 내부에서 사용
	}

	void speedDown() {
		speed -= 10;
		if(speed < 0) //속도가 -는 없으므로, 
			//speed = 0;
			stop(); //그냥 stop을 호출하면 됨
	}

	void stop() {
		speed = 0;
	}
}
public class CarUser{
	public static void main(String[] args) {
		Car car1 = null;//Car라는 객체를 만듦, 참조형은 아무것도 생성하지 않은 상태를 null이라고 한다. 힙 영역의 객체를 참조하지 않는다. cf)오라클 아직 알 수 없는 값
		car1 = new Car(); //새로운 객체 생성 , Car클래스에 만든 적은 없지만 자동으로 Car클래스에 자동으로 생성됨
		
		System.out.println("car1의 이름 : " + car1.carName); 
// 초기화를 하지 않으면 자동으로 초기화 (참조형 : null) (기본형 : int는 0, boolean은 false, double은 0.0, char는 초기화x공백)
		car1.carName = "쏘나타";
		System.out.println("car1의 이름 : " + car1.carName);
		car1.carColor = "흰색";
		System.out.println("car1의 색상 : " + car1.carColor);
		car1.maker = "현대";
		System.out.println("car1의 제조사 : " + car1.maker);
		car1.speed = 30;
		System.out.println("car1의 속도 : " + car1.speed);

		int cnt = 3;
		System.out.println("car1의 속도를 " + cnt + "회 증가!!");
		for (int i=0;i<cnt;i++){
			car1.speedUp();
		}
		//car1.speedUp();
		//car1.speedUp();//speedUp 메소드 호출
		System.out.println("car1의 속도 : " + car1.speed);

		cnt = 10;
		System.out.println("car1의 속도를 " + cnt + "회 감속!!");
		for (int i=0;i<cnt;i++)
			car1.speedDown(); //조건문 밑에 한줄일 경우에는 { } 생략 가능
		
		System.out.println("car1의 속도 : " + car1.speed);


		Car car2 = new Car();
		System.out.println("car2의 이름 : " + car2.carName); //쏘나타? null?

		Car car3 = car1;
		car3.carName = "K5";
		System.out.println("car1의 이름 : " + car1.carName); //객체는 주소값을 할당한다.car1의 주소값을 가져와서 변경하니까 K5출력

	}
}

 

---------- run ----------
car1의 이름 : null
car1의 이름 : 쏘나타
car1의 색상 : 흰색
car1의 제조사 : 현대
car1의 속도 : 30
car1의 속도를 3회 증가!!
car1의 속도 : 60
car1의 속도를 10회 감속!!
car1의 속도 : 0
car2의 이름 : null
car1의 이름 : K5

----------------------------------------------------------------------------------------------------------------------------

public class Car1 {
	int gas;

	void setGas(int gas){ //외부에서 입력한 값 받기
		this.gas = gas; // gas 필드에 외부에서 입력한 gas값을 저장
	}

	boolean isLeftGas(){
		if (gas == 0){
			System.out.println("gas가 없습니다.");
			return false;
		}
		System.out.println("gas가 있습니다.");
		return true; //리턴타입이 있으면 반드시 return문 존재!!
	}

	void run(){
		while(true) {
			if (gas>0){
				System.out.println("달립니다.(gas잔량 : " + gas + ")");
				gas -= 1;
			} else {
				System.out.println("멈춥니다.(gas잔량 : " + gas + ")");
				return;
			}
		}
	}
}
public class CarExample {
	public static void main(String[] args) {
		Car1 myCar = new Car1();

		myCar.setGas(5);

		boolean gasState = myCar.isLeftGas();
		if (gasState){
			System.out.println("출발합니다");
			myCar.run();
		}

		if (myCar.isLeftGas()){
			System.out.println("gas를 주입할 필요가 없습니다.");
		} else {
			System.out.println("gas를 주입할 필요가 있습니다.");
		}
	}
}
---------- run ----------
gas가 있습니다.
출발합니다
달립니다.(gas잔량 : 5)
달립니다.(gas잔량 : 4)
달립니다.(gas잔량 : 3)
달립니다.(gas잔량 : 2)
달립니다.(gas잔량 : 1)
멈춥니다.(gas잔량 : 0)
gas가 없습니다.
gas를 주입할 필요가 있습니다.

 ex)

public class Member {
	String name;
	String id;
	String password;
	int age;

	Member(String name, String id){
		this.name = name;
		this.id = id;
	}	
}
public class MemberService {
	boolean login(String id, String password){
		
		if (id.equals("hong") && password.equals("12345")){ //문자열 비교
			return true;
		} else {
			return false;
		}
	}

	void logout(String id){
		System.out.println("로그아웃 되었습니다.");
	}
}
public class MemberServiceExample {
	public static void main(String[] args) {
		MemberService ms = new MemberService();

		boolean result = ms.login("hong","12345"); //리턴 받을 변수 선언

		if (result){
			System.out.println("로그인 되었습니다.");
			ms.logout("hong");
		} else {
			System.out.println("id 또는 password가 올바르지 않습니다.");
			}
	}
}
---------- run ----------
로그인 되었습니다.
로그아웃 되었습니다.

 

(1) do ~ while문 : 선실행, 후조건, 최소 한번은 실행해야 하는 code

형식)

do {

실행문;

} while(조건식);

 

* while문과 비교

  • 0열 선택0열 다음에 열 추가
  • 1열 선택1열 다음에 열 추가
  • 0행 선택0행 다음에 행 추가
  • 1행 선택1행 다음에 행 추가
  • 2행 선택2행 다음에 행 추가
  • 3행 선택3행 다음에 행 추가

셀 전체 선택

열 너비 조절

행 높이 조절

while

do ~ while

선조건, 후실행

선실행, 후조건

 

반복횟수가 0이어도, 조건에 상관없이 무조건 한번은 실행됨

사용자가 입력한 수의 팩토리얼을 구하는 프로그램

메뉴를 나타내어 사용자의 입력을 처리하는 프로그램

(사용자의 입력을 받은 후에 계속 루프를 돌 것인지 판단할 때 사용)

public class DoWhileTest{
	public static void main(String[] args) {
		int x = 0;
		do{
			x = (int )(Math.random() *3);
			System.out.println("x :" + x);
		}
		while (x!=0); //0이 되면 종료
	}
}

- 로또 do~while문으로 풀기

/*while문은 앞에 난수발생을 반복해서 써줘야 하지만, 
do ~ while문은 선실행, 후조건이기 때문에 앞에서 초기화값을 지정하지 않아도 ok~*/

public class Lotto2{
	public static void main(String[] args) {
		int gameCnt = 5;
		System.out.println("===== 금주의 예상번호 =====");
		int n1,n2,n3,n4,n5,n6;
		for (int i = 1;i <=gameCnt ;i++ ){
			n1 = (int) (Math.random() * 45 + 1);
			do{
				n2 = (int) (Math.random() * 45 + 1);
			}
			while (n1 == n2);
		
			do{
				n3 = (int) (Math.random() * 45 + 1);
			}
			while (n1 == n3 || n2 == n3);
		
			do{
				n4 = (int) (Math.random() * 45 + 1);
			}
			while (n1 == n4 || n2 == n4 || n3 == n4);
		
			do{
				n5 = (int) (Math.random() * 45 + 1);
			}
			while (n1 == n5 || n2 == n5 || n3 == n5 || n4 == n5);
			
			do{
				n6 = (int) (Math.random() * 45 + 1);
			}
			while (n1 == n6 || n2 == n6 || n3 == n6 || n4 == n6 || n5 == n6);
			
			System.out.println(i + "게임 : " + n1 + "  " + n2 + "  " + n3 + "  " + n4 + "  " + n5 + "  " + n6);
			}	 
		}
	}

- 숫자 야구게임 (1번과 2번까지만 배움... 추후에 완성시키는 걸로~~)

/*
1. 컴이 서로 다른 3자리수를 발생 
	- 첫자리는 0이 되면 안된다.
	- 나머지는 0~9중의 난수.
2. 내가 입력한 수를 3개로 분리 (유효성검사 - 입력값이 적절한지)
3. 컴과 내가 입력한 수를 비교
 3-1. 숫자와 자리까지 맞으면 strike
 3-2. 숫자만 맞고 자리가 틀렸으면 ball
4. 결과 출력
 4-1. strike가 3이면.. xxx는 정답입니다.
 4-2. strike가 3이 아니면... xxx는 x스트라이크 X볼입니다.
*/

public class BaseBallGame{
	public static void main(String[] args) {
		int myNum = 729;
		int c1, c2, c3;
		int m1 = (myNum /100);
		int m2 = (myNum % 100 /10);
		int m3 = (myNum % 10);
		
		do{
			c1 = (int) (Math.random()*10);
		}
		while (c1 == 0);

		do{
			c2 = (int) (Math.random()*10);
		}
		while (c1 == c2);

		do{
			c3 = (int) (Math.random()*10);
		}
		while (c1 == c3 || c2 == c3);

		System.out.println("컴 : " +c1 + " " +c2+ " " +c3);//컴 : x x x
		System.out.println("나 : "+m1 + " " +m2+ " " +m3);//컴 : 7 2 9
		
	}
}

 

(2) break문 : 반복문인 for, while, do~while문을 실행 중지시킬 때 사용 (if문과 사용)

: if문의 조건문이 true라면, 아예 반복문을 빠져나오도록 설정!!

 

public class BreakExample{
	public static void main(String[] args) {
		while(true) {
			int num = (int) (Math.random()*6)+1;
			System.out.println(num);
			
			if (num == 6){ //6이 나오면 멈추고 while문을 빠져나가 "프로그램 종료"를 출력하라.
				break;
			}
		}
		System.out.println("프로그램 종료");
	}
}

 

(3) continue문 : 반복문인 for, while, do~while문에서만 사용 (if문과 사용)

if문의 조건문이 true라면 continue 아래는 실행되지 않고, 위로 반복문을 찾아 올라간다.

- for문 : 증감식으로 이동

- while, do~while문 : 조건식으로 이동

 

//무한루프

public class EtcTest{
	public static void main(String[] args) {
		boolean b = true;
		while (b) {
			int x = (int) (Math.random() *5); // 0~4
			if (x == 0){
				b = false;
			} else {
				System.out.println("10 / x :" + 10 / x);
			}
		}
		System.out.println("---------------------");
		while (true){
			int x = (int) (Math.random() *5);
			if (x == 0){
				System.out.println("0이 나와서 종료합니다.");
				break; //반복문을 빠져나오는 break, 주로 if문이랑 같이 쓰임
			}
			System.out.println("10 / x :" + 10 / x);

		}

		System.out.println("---------------------");
		for (int i = 0;i<10 ;i++ ){
			int x = (int) (Math.random() *5);
			if (x == 0){
				System.out.println("0이 나와서 종료합니다.");
				break;
			}
			System.out.println(i + 1 + ". 10 / x :" + 10 / x);
		}

		System.out.println("---------------------");
		for (int i = 0;i<10 ;i++ ){
			int x = (int) (Math.random() *5);
			if (x == 0){
				System.out.println("0이 나와서 다음으로 진행합니다.");
				continue;
			}
			System.out.println(i + 1 + ". 10 / x :" + 10 / x);
		}
	}
}
---------- run ----------
---------------------
10 / x :10
10 / x :10
10 / x :2
10 / x :3
10 / x :3
0이 나와서 종료합니다.
---------------------
0이 나와서 종료합니다.
---------------------
1. 10 / x :3
0이 나와서 다음으로 진행합니다.
3. 10 / x :3
4. 10 / x :3
5. 10 / x :3
6. 10 / x :5
7. 10 / x :5
8. 10 / x :3
0이 나와서 다음으로 진행합니다.
10. 10 / x :5

 

(1) while문 : 횟수가 안 정해져 있을 때(for문과 차이점), only 조건만 참조,

조건을 만족 하지 않으면 한 번도 실행이 안 될 수도 있다!!!

형식)

while (조건식) {

실행문;

}

 

public class  WhileTest{
	public static void main(String[] args)  {
		System.out.println(" 1~10까지 출력!!!" ); //for문으로 쓰는 게 더 효율적
		int x = 1;
		while (x<=10){
			System.out.println(x++); //그냥 x만 하면 1씩 증가하지 않아, 1만 계속 출력됨
		}

		System.out.println(" 1~10까지 출력!!!(홀수만)" );
		 int a = 1;
		 while (a<=10) {
			 if (a%2==1) {
				System.out.println(a);
			 }
				a++; // a= a+1 or a+=2;
		 }

		 int y = 10;
		 int z = (int) (Math.random()*10); // 0-9
		 while (z !=0){ //어떤 숫자를 0으로 나눌 수 없기 때문에 이렇게 처리
			System.out.println(y + "/" + z + " = " + y / z);
			z = (int) (Math.random() * 10);
		 }
	}
}
---------- run ----------
 1~10까지 출력!!!
1
2
3
4
5
6
7
8
9
10
 1~10까지 출력!!!(홀수만)
1
3
5
7
9
10/4 = 2
10/5 = 2
10/1 = 10
10/3 = 3

- 로또 게임 (배열 사용 x)

/*
1. 1~45의 중복되지 않는 난수 6개
2. 1의 발생 숫자를 정렬 (나중에...)
3. 게임수 (5판)
결과>
1게임 : 5 10 13 26 85
2게임 :'
.
.
5게임 : 2 4 9 2 15 95
*/

//로또는 계속 반복되기 때문에 if문으로 하기에는 부적합. while로 처리하기.(횟수를 모르는 계속 반복되는 식)

public class  Lotto{
	public static void main(String[] args)  {
		int gameCnt = 5;
		System.out.println("===== 금주의 예상번호 =====");
		int l1,l2,l3,l4,l5,l6;
		for (int i=1;i<=gameCnt ;i++ ){
			
		 l1 = (int) (Math.random()*45)+1;
		 l2 = (int) (Math.random()*45)+1;
		 l3 = (int) (Math.random()*45)+1;
		 l4 =(int) (Math.random()*45)+1;
		 l5 =(int) (Math.random()*45)+1;
		 l6 =(int) (Math.random()*45)+1;
		
		while(l1==l2) { //중복제거
			l2 = (int) (Math.random()*45)+1;
		}
		while(l1==l3 || l2 == l3) {
			l3 = (int) (Math.random()*45)+1;
		}
		while(l1==l4 || l2 ==l4 || l3 == l4) { 
			l4 = (int) (Math.random()*45)+1;
		}
		while(l1==l5 || l2 == l5 || l3 == l5 || l4 == l5) { 
			l5 = (int) (Math.random()*45)+1;
		}
		while(l1==l6 || l2 == l6 || l3 == l6 || l4 == l6 || l5 == l6) { 
			l6 = (int) (Math.random()*45)+1;
		}
		System.out.println(i +"게임 : " +l1+ " " + l3 + " " + l4+ " " + l5+ " " + l6 );
		}			
	} 
}

- 구구단 소스 (while문)

public class  GugudanWhileTest{
	public static void main(String[] args)  {
		int dan = 2;
		int i = 1;
		while (dan<=9){ 
			while (i<=9){
				System.out.print(dan + " * " + i+ " =  " + dan*i + "  ");
				i++; 
			}
			i = 1;
			System.out.println();
			 dan++;
		} 
		
	}
}
---------- run ----------
2 * 1 =  2  2 * 2 =  4  2 * 3 =  6  2 * 4 =  8  2 * 5 =  10  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 * 5 =  15  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 * 5 =  20  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 * 5 =  25  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 * 5 =  30  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 * 5 =  35  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 * 5 =  40  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 * 5 =  45  9 * 6 =  54  9 * 7 =  63  9 * 8 =  72  9 * 9 =  81  

- 두개의 주사위를 던졌을 때 나오는 눈을 (눈1, 눈2)로 출력하고, 눈의 합이 5가 아니면 계속 주사위를 던지고, 눈의 합이 5이면 실행을 멈추어라. (while문 사용)

public class  Example {
	public static void main(String[] args)  {
		/*int a = 3;
		int b = 3;
		while (a+b != 5){
			a = (int) (Math.random()*6)+1;
			b = (int) (Math.random()*6)+1;
			System.out.println ("(" + a + " , " + b + ")");
		} */

//while & break 사용
		while (true){
			int a = (int)(Math.random()*6)+1;
			int b = (int)(Math.random()*6)+1;
			System.out.println(" (" +a+", "+ b + " )");
			if (a+b ==5){
				break;
			}
		}
	}
}

- while & 증감연산자

public class While1{
	public static void main(String[] args) {
		int j=1, i=1, k=1;
		int sum1=0;
		int sum2=0;
		int sum3 = 0;

		while (j<=10){
			sum1 = sum1 +(j++); // 1~10까지 결과 : 55
		}

		while (i<=10){
			sum2 = sum2 +(++i); // 1~11까지 결과 : 65
		}

		while (k<10){
			sum3 = sum3 +(k++); // 1~9까지 결과 : 45
		}
		System.out.println(sum1);
		System.out.println(sum2);
		System.out.println(sum3);
	}
}

 

(1) 반복문

1. for문 : 규칙 반복시, 횟수가 정해진 경우 사용 (이중 , 삼중 for문이 가능하다!!!!)

형식)

for(초기화;조건식;증감식) {

// 초기화는 처음 한 번만 실행. 조건식: 참or거짓 --> 참이면 실행문 --> 증감식 --> 다시 조건식 --> 거짓이 나올 때까지 반복

실행문;

}

 

ex1)

1~10까지 출력하시오. >> 횟수 o, 규칙 o

for (int i = 1;i<11;i++) {

System.out.println(i);

}

 

ex2)

자연수 2 8 5 1 9를 출력하시오. >> 횟수 o, 규칙 x

public class ForTest {
	public static void main(String[] args) {
		System.out.println("1 ~ 10까지 출력!!!");
		for(int i=1;i<11;i++) {
			System.out.println(i);
		}
		System.out.println("1 ~ 10까지의 홀수만 출력!!!"); 
		//방법1
            for(int i=1;i<11;i++) { //10번 실행됨, 시간이 오래걸림
			if(i % 2 != 0) {
				System.out.println(i);
			}
		}
		System.out.println("---------------------------");
		//방법2
            for(int i=1;i<11;i+=2) { //5번 실행됨, 시간 절약, 더 효율적
			System.out.println(i);
		}
        //방법3
            for (int i=1;i<=10;i++){
                if (i%2==0){ //짝수라면 밑에 i에 대입이 안되고, i++로 올라감
				   continue;
                 } 
            System.out.println(i);
             }

		int dan = 7;
		System.out.println("*** " + dan + "단 ***");
		// 7 * 1 = 7
		// 7 * 2 = 14
		// .
		// 7 * 9 = 63
		for(int i=1;i<10;i++) {
			System.out.println(dan + " * " + i + " = " + dan * i);
		}
        
        //i가 5일때, 줄바꾸기 (for문 안에 if문 쓰기)
		for(int i=1;i<10;i++) {
			System.out.print(dan + " * " + i + " = " + dan * i + "  ");
			if(i == 5) {
				//System.out.print("\n");
				System.out.println();
			}
		}

		System.out.println("1 ~ 100까지 출력!!(10자리마다 줄바꿈)");
		for(int i=1;i<101;i++) {
			System.out.print(i);
			if(i % 10 != 0) { //10이 아닐 경우를 먼저 하는 게 효율적
				System.out.print("  "); 
			} else {
				System.out.print("\n");//10인 경우 줄을 바꿈
			}
		}
	}
}
---------- run ----------
1~10까지 출력!!!
1
2
3
4
5
6
7
8
9
10
1~10까지의 홀수만 출력!!!
1
3
5
7
9
***7단 ***
7*1=7
7*2=14
7*3=21
7*4=28
7*5=35
7*6=42
7*7=49
7*8=56
7*9=63
7*1=7  7*2=14  7*3=21  7*4=28  7*5=35  7*6=42  7*7=49  7*8=56  7*9=63  7*1=7  7*2=14  7*3=21  7*4=28  7*5=35  
7*6=42  7*7=49  7*8=56  7*9=63  1~100까지 출력!!(10자리마다 줄바꿈)
1  2  3  4  5  6  7  8  9  10
11  12  13  14  15  16  17  18  19  20
21  22  23  24  25  26  27  28  29  30
31  32  33  34  35  36  37  38  39  40
41  42  43  44  45  46  47  48  49  50
51  52  53  54  55  56  57  58  59  60
61  62  63  64  65  66  67  68  69  70
71  72  73  74  75  76  77  78  79  80
81  82  83  84  85  86  87  88  89  90
91  92  93  94  95  96  97  98  99  100

 

 

**<구구단 만들기>

 

- 단별로 세로로 출력

public class Gugudan1 {
	public static void main(String[] args) {
		System.out.println("*** 구구단 ***");
		for(int dan=2;dan<10;dan++) { //2단일때, 밑에 for문에서 1~9까지 실행
			for(int i=1;i<10;i++) {
				System.out.print(dan + " * " + i + " = " + dan * i + "  ");
			}
			System.out.println();
		}
	}
}
---------- run ----------
 *** 구구단 *** 
2 * 1 = 2  2 * 2 = 4  2 * 3 = 6  2 * 4 = 8  2 * 5 = 10  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 * 5 = 15  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 * 5 = 20  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 * 5 = 25  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 * 5 = 30  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 * 5 = 35  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 * 5 = 40  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 * 5 = 45  9 * 6 = 54  9 * 7 = 63  9 * 8 = 72  9 * 9 = 81   

- 단별로 가로로 출력

public class Gugudan2 {
	public static void main(String[] args) {
		System.out.println("*** 구구단 ***");
		for(int i=1;i<10;i++) {
			for(int dan=2;dan<10;dan++) {
				System.out.print(dan + " * " + i + " = " + dan * i + "  ");
			}
			System.out.println();
		}
	}
}
---------- run ----------
*** 구구단 ***
2 * 1 = 2  3 * 1 = 3  4 * 1 = 4  5 * 1 = 5  6 * 1 = 6  7 * 1 = 7  8 * 1 = 8  9 * 1 = 9  
2 * 2 = 4  3 * 2 = 6  4 * 2 = 8  5 * 2 = 10  6 * 2 = 12  7 * 2 = 14  8 * 2 = 16  9 * 2 = 18  
2 * 3 = 6  3 * 3 = 9  4 * 3 = 12  5 * 3 = 15  6 * 3 = 18  7 * 3 = 21  8 * 3 = 24  9 * 3 = 27  
2 * 4 = 8  3 * 4 = 12  4 * 4 = 16  5 * 4 = 20  6 * 4 = 24  7 * 4 = 28  8 * 4 = 32  9 * 4 = 36  
2 * 5 = 10  3 * 5 = 15  4 * 5 = 20  5 * 5 = 25  6 * 5 = 30  7 * 5 = 35  8 * 5 = 40  9 * 5 = 45  
2 * 6 = 12  3 * 6 = 18  4 * 6 = 24  5 * 6 = 30  6 * 6 = 36  7 * 6 = 42  8 * 6 = 48  9 * 6 = 54  
2 * 7 = 14  3 * 7 = 21  4 * 7 = 28  5 * 7 = 35  6 * 7 = 42  7 * 7 = 49  8 * 7 = 56  9 * 7 = 63  
2 * 8 = 16  3 * 8 = 24  4 * 8 = 32  5 * 8 = 40  6 * 8 = 48  7 * 8 = 56  8 * 8 = 64  9 * 8 = 72  
2 * 9 = 18  3 * 9 = 27  4 * 9 = 36  5 * 9 = 45  6 * 9 = 54  7 * 9 = 63  8 * 9 = 72  9 * 9 = 81  
public class ForExample{
	public static void main(String[] args) {
		System.out.println("1부터 100까지 더하라");
		int sum = 0;

		for (int i =1;i<=100 ;i++ ){
			sum += i;
		}
		System.out.println(sum);	
	}
}
---------- run ----------
1부터 100까지 더하라
5050

 

- 중첩 for문 사용

ex) 4x + 5y = 60의 모든 해를 구해서 (x,y)형태로 출력하시오. x와 y는 10이하의 자연수입니다.

public class Exercise05{
	public static void main(String[] args) {
	
		for (int x=1;x<=10 ;x++ ){
			for (int y=1;y<=10 ;y++ ){
			
				if (4*x+5*y == 60){
					System.out.println("(" +x+" , " + y + ")");
				}
			}
		}
	}
}
---------- run ----------
(5 , 8)
(10 , 4)

 

- for문 이용 삼각형 출력

/*
*
**
***
****
*****
삼각형 출력하기
*/

public class Exercise06{
	public static void main(String[] args) {
	
		int a = 5;
		for (int i=1;i<=a ;i++ ){
			for (int j=1;j<=i ;j++ ){
				System.out.print("*");
			if (i==j){ //i가 1번 실행되면 j는 * 1개, i가 2번 실행되면 j는 * 2개, i=j랑 같을 때 개행 
				System.out.println();
			}	
			}
		}
	}
}

 

 

 

 

(1) eclipse.exe 실행

 

- workspace : 이클립스에서 생성한 프로젝트가 기본적으로 저장되는 디렉토리

Q. 저장 위치 변경하고 싶다면? file - switch workspace - other

 

- perspective : 개발 프로젝트 종류별로 유용한 view들을 묶어 놓은 것

 

- window탭에서 open perspective - java 클릭

 

(2) 프로젝트 생성

 

1. file - new - java project 클릭

2. project name : chap01 입력

3. next - finish

 

(3) 소스 파일 생성과 컴파일

 

1. 왼쪽 package explorer에서 chap01 - src - 마우스 오른쪽 버튼 클릭 - new - class 선택

2. package 이름 지우기

3. name : Hello 입력

4. finish

5. main method 작성

public class Hello {
	public static void main (String args[]) {
		System.out.println("Hello,welcome to the Java World");
	}
}

 

6. 저장 (자동 compile)

7. 실행

 

(4) 글꼴 변경하기

 

window - preferences - general - appearance - colors and fonts - basic - text font 클릭 후 edit

 

(5) 라인 번호 생성

 

작업창에서 마우스 오른쪽 버튼 누르면 show line numbers 클릭

 

(6) 패키지 생성

java project chap02 생성 - chap02 src 오른쪽 마우스 클릭 후 - new - package - name : sec01 - finish

서브패키지 생성 : sec01에서 오른쪽 마우스 클릭 후 new package - name : sec01.exam01_variable - finish

서브패키지에 오른쪽 마우스 클릭 후 class 선택 - name : VariableExample - finish

package sec01.exam01_variable;
public class VariableExample {
	public static void main(String args[]) {
		int value = 10;
		int result = value + 10;
		System.out.println(result);
	}
}
20

 

 

 

(1) ascii code 값 외우기

'0' = 48번

'1 = 49번

'2' = 50번

'A' = 65번

'a' = 97번

 

(2) **타입변환

자동(묵시적) 타입 변환 : Promotion

강제(명시적) 타입 변환 : Casting

 

- 자동 타입 변환 : 프로그램 실행 도중에 작은 타입은 큰 타입으로 자동 타입 변환이 된다

byte(1) < short(2) < int(4) < long(8) < float(4) < double(8)

 

- 강제 타입 변환 : 작은크기타입 = (작은크기타입) 큰크기타입

(원래 값이 보존될 것인지, 손실될 것인지 if문으로 검사!!)

 

package sec03.exam02_casting;

public class CheckValueBeforeCasing {

	public static void main(String[] args) {

		/*int i = 128;
		byte b = (byte) i;//byte가 -128~127까지만 가능, 결과 : -128
		System.out.println(b);*/
		
		int i = 128;
		if(i<-128 || i>127) { // 둘 중 하나라도 true면 true
        //or if(i<Byte.MIN_VALUE || i>Byte.MAX_VALUE)
			System.out.println("byte 타입으로 변환할 수 없습니다.");
			System.out.println("값을 다시 확인해 주세요.");
		} else {
			byte b = (byte) i; 
			System.out.println(b);
		}
	}
}
byte 타입으로 변환할 수 없습니다.
값을 다시 확인해 주세요.

ex)

public class CastingTest {
  public static void main(String[] args) {
    double d = 123.56;
      System.out.println("d:" + d);

//int x = d; double은 8byte고, int는 4byte라서 오류!!

int x = (int) d; // casting 연산 (강제형변환) - 기본형은 기본형끼리, 참조형은 참조형끼리만 변환
      System.out.println("x:" + x);

   d = x; // (자동형변환 - 작은 값을 큰 값에 집어넣는 거니까 오류x)
      System.out.println("d:" + d);
  /*boolean b = true;
   int y = b;
  */ // 값은 타입만 형 변환 가능하기 때문에 오류

   char c = 'a';
   int y = c;
      System.out.println("y:" + y); // ascii 코드 값을 가지기 때문에 ok

   c = (char)y; // (강제형변환)
      System.out.println("c:" + c);
 } 
}
---------- run ----------
d:123.56
x:123
d:123.0
y:97
c:a

ex)

package sec01.exam01_variable;

public class VariableExample {
	public static void main(String args[]) {
		byte var1 = 10;
	    //var1 = var1 + 1; //산술연산은 int 값으로 나오기 때문에 byte 변수 var1에 대입할 수 x
        var1 ++; // or var1 = (byte) (var1 + 1); or int intvar1 = var1 + 1;
		System.out.println(var1);

        int intValue1 = 10;
		int intValue2 = intValue1 / 4; // 정수 / 정수
		System.out.println(intValue2); // 값 : 2 정수로 계산됨
		
		int intValue3 = 10;
		//int intValue4 = 10 / 4.0; (산술연산이지만 실수값이 들어갔기 때문에 double로 자동 변환)
		double doubleValue = intValue3 / 4.0; // 정수 / 실수 = 실수
		System.out.println(doubleValue); //값 : 2.5
	}
}

 

** ex1)

/*

가위 바위 보

1. 가위(0), 바위(1), 보(2)

2. 컴퓨터는 0,1,2중 하나의 난수 발생

3. 나는 0,1,2 중 하나의 수를 입력

4. logic

5. 결과 >> 나 : 바위, 컴 : 가위, 결과 : 이겼다.

*/

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

public class GBB {
    public static void main(String[] args) {
        //double d = Math.random();//0.0<= Math.random() < 1.0
        //System.out.println(d);
        int com = (int) (Math.random() * 3);//0 1 2
        int my = 1;
        int result = (my - com + 2) % 3;

        String myStr;
        String comStr;
        String resultStr;
        if(my == 0) {
            myStr = "가위";
        } else if(my == 1) {
            myStr = "바위";
        } else {
            myStr = "보";
        }

        switch(com) {
            case 0 : comStr = "가위"; break;
            case 1 : comStr = "바위"; break;
            default : comStr = "보";
        }

        if(result == 0) {
            resultStr = "이겼다.";
        } else if(result == 1) {
            resultStr = "졌다.";
        } else {
            resultStr = "비겼다.";
        }    

        System.out.println("나 : " + myStr + ", 컴 : " + comStr + ", 결과 : " + resultStr);//나 : 바위, 컴 : 가위, 결과 : 이겼다.
    }
}

ex2) 주사위 던지기

public class  IfDiceExample{
	public static void main(String[] args)  {
		int num = (int) (Math.random() * 6) +1; // 1부터 나오게 하려면 +1, 0부터 나오게 하려면 그냥 *만!!

		if (num == 1)	{
			System.out.println ("1번이 나왔습니다.");
		} else if (num ==2)	{
			System.out.println ("1번이 나왔습니다.");
		} else if (num ==3)	{
			System.out.println ("3번이 나왔습니다.");
		}else if (num ==4)	{
			System.out.println ("4번이 나왔습니다.");
		}else if (num ==5)	{
			System.out.println ("5번이 나왔습니다.");
		}else {
			System.out.println ("6번이 나왔습니다.");
		}

		}
	}

public class SwitchExample{
	public static void main(String[] args) {
		int num = (int) (Math.random()*6)+1; // 1~6까지 나온다.
		
		switch (num){
		case 1: System.out.println("1번이 나왔습니다.");break;
		case 2: System.out.println("2번이 나왔습니다.");break;
		case 3: System.out.println("3번이 나왔습니다.");break;
		case 4: System.out.println("4번이 나왔습니다.");break;
		case 5: System.out.println("5번이 나왔습니다.");break;
		default: System.out.println("6번이 나왔습니다.");
		
		}

	}
}

+ Recent posts