2022.09.16 JAVA-2

차유빈·2022년 9월 16일
0

JAVA

목록 보기
2/13

while 반복문

  • While(조건문) { 명령문; }
  • 중지 버튼을 눌려주지 않으면 계속 반복


조건문


증가 감소 연산자(Increment)

  • 1씩 증가 : 변수 +=1 / 변수 ++ / ++변수
  • 1씩 감소 : 변수 -=1 / 변수 -- / --변수


증감연산자 위치 앞 뒤

package application;

public class PreAndPost {

	public static void main(String[] args) {
		//증감연산자 위치 전 후
		int cat = 5;
		System.out.println(cat++); //연산 수행 후 1 증가 이므로 5로 출력
		System.out.println(cat); //1 증가된 6으로 출력
		
		int dog = 3;
		System.out.println(++dog); //연산 수행 전 1증가 되므로 4로 출력
		System.out.println(dog); //처음부터 1증가이니깐 4

		int chicken = 10;
		
		int animal = cat + chicken++;
		System.out.println(animal); 
		//cat 6 + chicken 10 = 16마리, 다음에 chicken은 11
		
		int apple = 5;
		int banana = 4;
		
		int fruit = ++apple + banana++;  
		//apple 6 + banana 4 = 10, 다음에 banana는 5
		System.out.println(fruit); 
	}
}


for 반복문

  • for( 변수 ; 조건 ; 증감 ) { 명령문; }
package application;

public class For {

	public static void main(String[] args) {
		// for 반복문
		int total = 0;
		for(int i = 1; i <= 100 ; i++ ) {
			total = total + i;
			// total += i;
		}
		System.out.println(total);
	}
}


boolean (불린 타입)

  • boolean 변수 = 조건


If문

  • if(조건문) { 명령문 };
package application;

import java.util.Scanner;

public class If {

	public static void main(String[] args) {
		//if 조건문
		int apple = 10;
		int banana = 5;
		
		if(apple > banana) {
			System.out.println("사과가 바나나보다 많음");
		}
		
		System.out.println("프로그램 종료!");
		
		Scanner scanner = new Scanner(System.in);
		System.out.printf("사과의 개수는 ? ");
	    int Apple = scanner.nextInt();
		System.out.printf("바나나의 개수는 ? ");
	    int Banana = scanner.nextInt();
	    
	    if(Apple > Banana) {
			System.out.println("사과가 바나나보다 많음");
	    }
			if(Apple < Banana) {
				System.out.println("바나나가 사과보다 많음");
			}
		} 	    
	}

if else 문

If else if else문


예제

package application;

import java.util.Scanner;

public class Ex1 {

	public static void main(String[] args) {
		// 예제 1	
		
		System.out.println("메뉴 \n====\n");
		System.out.println("1. 프린트 '헬로우'");
		System.out.println("2. 프린트 '안녕 ?'");
		System.out.println("3. 프로그램 종료\n");
		System.out.printf("옵션을 선택 > ");
		
		Scanner scanner = new Scanner(System.in); //scanner를 부르기 전에 언급
		int a = scanner.nextInt();
		
		if (a==1) {
			System.out.println("헬로우");
		}
		else if(a==2) {
			System.out.println("안녕 ?");
		}
		else if(a==3) {
			System.out.println("프로그램 종료");
		}
		else if(a==10000) {
			System.out.println("이스터에그를 발견했습니다.");
		}
		else {
			System.out.println("잘못된 옵션입니다.");
		}
	}
}

if문 switch문으로 바꾸기


Switch문 1 (변수 값이 숫자 일 때)

  • switch(변수) { case 변수값 : 명령문 };
  • 괄호 안의 (변수)값이 case 변수값 과 같을 시 명령문 실행
  • if문은 비교하여 true, false에 따라 명령문 실행하지만 switch문은 변수 데이터 값이 동일할 때 명령문 실행함
    (즉, case가 여러개이고 변수값이 같을 경우 사용하면 좋음)
package application;

public class Switch {

	public static void main(String[] args) {
		// Switch 문은 if else 문 대체 가능
		
		int option = 5; // 언급한 case 변수값 부터 반환 시작
		
		switch(option) {
		case 0 :
			System.out.println("옵션 0 선택.");
			break; //종료
		case 1 :
			System.out.println("옵션 1 선택.");
			break; 
		case 10 :
			System.out.println("옵션 10 선택.");
			break; 
		default:
			System.out.println("없는 옵션입니다.");
			break;
		}
	}
}


Switch문 2 (변수값이 문자열 일 때)

package application;

import java.util.Scanner;

public class Switch2 {

	public static void main(String[] args) {

		System.out.println("계속 진행 하시겠습니까? (y/n): ");
		
		Scanner scanner = new Scanner(System.in);
		String input = scanner.nextLine(); //문자열 입력가능
		//System.out.println(input);
		switch(input) {
		case "y" :
			System.out.println("진행합니다.");
			break;
		case "n" :
			System.out.println("종료합니다.");
			break;
		default :
			System.out.println("잘못된 입력입니다.");
			break;
		}
	}
}


문자열 비교

  • 같으면 true, 틀리면 false
  • 변수 1.equal(변수 2)

문자열 비교는 equals 메소드 사용해야함!


Final 상수

  • 변수 앞에 final을 붙여주면 상수 값으로 변함(변수 값을 바꿀 수 없음)


break (반복문 빠져나오기)


CheckPassword


Do while 문 (반복)

  • 조건에 관계 없이 처음 한번은 무조건 실행 됨
  • 조건이 맞을 때까지 무한 반복

do while문을 이용한 password 판별

package application;

import java.util.Scanner;

public class CheckPasswordDoWhile {

	public static void main(String[] args) {
		// 입력한 패스워드를 설정 패스워드와 비교
		final String PASS = "1234";
		
		Scanner scanner = new Scanner(System.in);
		
		String password = null;
		do {
			System.out.println("패스워드 : ");
			password = scanner.nextLine();
		} while (!password.equals(PASS)); 
		// 입력한 password와 PASS 변수의 데이터 값이 틀리면 무한 반복
		// 맞으면 "접속 승인" 반환
		System.out.println("접속 승인");
	}
}


Scope (변수 범위)

  • 지역 변수 : 코드 블럭 { } 안에서 선언된 변수는 밖에서 사용 불가
  • 전역 변수 : 밖에서 선언된 변수는 코드 블럭 { } 안에서 사용 가능
    예로 do while 문에서 do의 코드 블럭 { } 내의 변수와 이어지는 밖의 while () 변수 값을 비교해야 하므로 써야함
package application;

import java.util.Scanner;

public class Scope {

	public static void main(String[] args) {

		// 지역 변수
		{
			int value = 0; // { } 코드 블럭 안에서만 사용 가능
			System.out.println(value);
		}
		   //System.out.println(value);
		
		Scanner scanner = new Scanner(System.in);
		
		for(int i = 0; i < 4 ; i++) {
			System.out.println(i); // for문의 { } 코드 블럭 안에서만 사용 가능
		}
			// System.out.println(i);
		
		// 전역 변수
		String input = null; // do { }안에서 사용 가능
		do {
			System.out.println("종료하려면 'stop'입력");
			input = scanner.nextLine();
		} while (!input.equals("stop"));	
		
	}
}


비밀번호 3회까지 승인


import java.util.Scanner;

public class PassWordCheckLimit {

	public static void main(String[] args) {
		// 입력한 패스워드를 설정 패스워드와 비교
		final String PASS = "1234";
		
		Scanner scanner = new Scanner(System.in);
		
		boolean accessOK = false; //초기 값은 false이고 맞췄을 때 true
		String password = null;
		
		for (int i = 1; i <= 3 ; i++) {
			System.out.printf("비밀번호 입력 : ");
			password = scanner.nextLine();
			if (password.equals(PASS)) {
				System.out.println("접속승인");
			    accessOK = true;
				break;
			} else {
				System.out.println("비번이 틀렸습니다.");
			}
			
		}
		
		if (accessOK == false) {
			System.out.println("접속거부");
		}
	}
}


배열 (정수)

  • 같은 타입의 여러 변수를 하나로 묶은 자료형(참조 자료형)
  • '[ ]' 으로 표기

배열 (문자열)

Loop Array (반복문과 배열)

New Array

  • 배열을 만들어 놓기만 하는 것(데이터 개수랑)
package application;

public class NewArray {

	public static void main(String[] args) {
		// new 키워드로 배열 생성
		// int[] numbers = {}; 초기값을 바로 넣는 방법
		int[] numbers = new int[3]; // 3개짜리 데이터의 정수 아이템 방 생성
		String[] strs = new String[3]; //3개 데이터의 문자열 아이템 방 생성 
		
		for(int i = 0; i < numbers.length; i++) {
			//값을 입력하지 않았을 때 int(정수)의 default 값은 0
			System.out.println(numbers[i]);
		}
		for(int i = 0; i < strs.length; i++) {
			System.out.println(strs[i]);
			//값을 입력하지 않았을 때 String(문자열)의 default 값은 null
		}	
	}

New Array 예제

  • scanner.close(); : 입력을 더 이상 받지 않을 때 닫아주는 역할(메모리 중단?)

profile
chacha's 프로그래밍 공부

0개의 댓글

Powered by GraphCDN, the GraphQL CDN