본문 바로가기
Java/생활코딩

Java 제어문

by k-mozzi 2022. 9. 18.
반응형
Preface

 

자바의 기본적인 제어문 사용 방법을 공부했다.

 

파이썬과 크게 다른 부분이 없어 쉽게 이해하고 넘어갈 수 있었다.

 

다만 파이썬에선 배열의 원소로 배열을 만들 때 별다른 작업이 필요 없었지만, 자바에선 대괄호 두 개를 사용해야 한다는 점이 조금 불편했다.


 

1. Conditional Statements

 

 

- Boolean 데이터 타입의 출력 형식

1) true

2) false

→ 위와 같은 예약어는 변수명으로 사용할 수 없다.

 

 

- 조건문 형식

public class IfApp {

	public static void main(String[] args) {

		if (false) {
			System.out.println(1);
		} else if (true) {
			System.out.println(2);
		} else {
			System.out.println(3);
		}

	}

}

 

 

- 'equals 메소드'는 비교 대상의 내용 자체를 비교하지만 '== 연산자'는 비교 대상의 주소값을 비교한다.

→ 디버깅을 통해 각 변수의 주소값을 확인할 수 있다.

public class AuthApp {

	public static void main(String[] args) {

		String id = "gang";
		String inputId = args[0];

		String pass = "1111";
		String inputPass = args[1];

		System.out.println("Hi.");

		// if (inputId == id) {
//		if (inputId.equals(id)) {
//			if (inputPass.equals(pass)) {
//				System.out.println("Master!");
//			} else {
//				System.out.println("Wrong password!");
//			}
//		} else {
//			System.out.println("Who are you?");
//		}

		if (inputId.equals(id) && inputPass.equals(pass)) {
			System.out.println("Master!");
		} else {
			System.out.println("Who are you?");
		}

	}

}

 

 

- 원시(primitive) 데이터 타입

1) boolean

2) int

3) double

4) short

5) long

6) float

7) char

 

 

- non primitive data type

1) String

2) Array

3) Date

4) File etc.

 

 

- new 키워드를 이용해 새로운 객체를 생성하면 같은 값이라도 서로 다른 메모리 주소를 참조하므로 '동등비교(==) 연산자'로 값을 비교했을 때 false가 출력된다.

 

 

- String 타입은 자주 사용되는 데이터 타입이므로 new 키워드 없이 같은 값을 가진 변수를 생성하면 새로운 메모리 주소를 할당하는 것이 아닌 기존의 메모리 주소를 가리킨다.

→ 자바 내부적으로 입력값을 다른 곳에 저장할 수도 있으므로 primitive 데이터 타입이 아닌 데이터들은 equals를 사용해 값을 비교하는 것이 좋다.

 

 

- 논리 연산자(logical operator)

1) and(&&): 두 값이 모두 참일 때 참

2) or(||): 두 값 중 한 가지만 참이어도 참

3) not(!): 반대 값일 때 참

public class LogicalOperatorApp {

	public static void main(String[] args) {

		// AND
		System.out.println(true && true);
		System.out.println(true && false);
		System.out.println(false && true);
		System.out.println(false && false);
		System.out.println("");
		
		// OR
		System.out.println(true || true);
		System.out.println(true || false);
		System.out.println(false || true);
		System.out.println(false || false);
		System.out.println("");
		
		// NOT
		System.out.println(!true);
		System.out.println(!false);

	}

}

 


 

2. Looping Statements

 

 

- while문과 for문의 형식

public class LoopApp {

	public static void main(String[] args) {

		System.out.println(1);

		int i = 0;
		while (i < 3) {
			System.out.println(2);
			System.out.println(3);
			i++;
		}

		for (int j = 0; j < 3; j++) {
			System.out.println(2);
			System.out.println(3);
		}

		System.out.println(4);

	}
}

 

 

- 배열 생성하는 형식


public class ArrayApp {

	public static void main(String[] args) {

		// 배열을 생성한 후 값 할
		String[] users = new String[3];
		users[0] = "gyeongmo";
		users[1] = "jaewhee";
		users[2] = "donghyeon";

		System.out.println(users[2]);
		System.out.println(users.length);

		// 배열을 생성하며 곧바로 값 할당
		int[] scores = {10, 100, 100};
		System.out.println(scores[1]);
		System.out.println(scores.length);
	}

}

 

 

- 배열과 반복문을 함께 사용하는 방법

public class LoopArray {

	public static void main(String[] args) {

		String[] users = new String[3];
		users[0] = "gyeongmo";
		users[1] = "jaewhee";
		users[2] = "donghyeon";

		for (int i = 0; i < 3; i++) {
			System.out.println(users[i]);
		}

	}

}

 

 

- 배열과 제어문을 사용해 로그인을 하는 프로그램

public class AuthApp3 {

	public static void main(String[] args) {

//		String[] users = { "gyeongmo", "jaewhee", "donghyeon" };
		String[][] users = {
				{"gyeongmo", "1111"},
				{"jaewhee","2222"},
				{"donghyeon", "3333"}
		};
		// 대괄호를 두 개 치면 배열 안에 또다른 배열을 만들 수 있다. 즉, 배열의 원솟값이 배열이다.

		String inputId = args[0];
		String inputPass = args[1];

		boolean isLogined = false;
		for (int i = 0; i < users.length; i++) {
			String[] current = users[i];
			if (
					current[0].equals(inputId) && 
					current[1].equals(inputPass)
			) {
				isLogined = true;
				break;
			}
		}
		System.out.println("Hi.");
		if (isLogined) {
			System.out.println("Master!");
		} else {
			System.out.println("Who are you?");
		}
	}

}

 

 

 

출처: https://www.youtube.com/playlist?list=PLuHgQVnccGMCoEXnWV8-UF1mBxK5ftmxH 

 

JAVA 제어문

 

www.youtube.com

 

728x90
반응형

'Java > 생활코딩' 카테고리의 다른 글

Java 객체 지향 프로그래밍  (0) 2022.09.25
Java 메소드  (2) 2022.09.20
Java 입문 수업 (4)  (2) 2022.09.15
Java 입문 수업 (3)  (0) 2022.09.12
Java 입문 수업 (2)  (0) 2022.09.11

댓글