[Java] 조건문, 반복문

HodooHa·2024년 4월 21일

조건문

1. if, if~else문

  • if(조건식) {...} : 조건식이 true가 되면 중괄호 내부를 실행한다.
  • if(조건식) {...} else {...} : 조건식이 truie가 되면 if 중괄호 내부를 실행한다. 조건식1과 조건식2가 모두 false가 되면 else 중괄호 내부가 실행된다.

2. switch문

  • switch(변수) {case 값1: ... case 값2: ... default: ...} :
    변수의 값이 값1이면 첫번째 case 코드를 실행, 값2이면 두번째 case 코드를 실행한다. 모두 아니면 default 코드를 실행한다.

반복문

1. for문

  • for(초기화식; 조건식; 증감식) {...} :
    조건식이 true가 될 때까지만 중괄호 내부를 반복한다. 반복할 때마다 증감식이 실행된다. 초기화식은 조건식과 증감식에서 사용할 루프 카운터 변수를 초기화한다. 주로 지정된 횟수만큼 반복할 때 사용한다.

2. while, do-while문

  • while(조건식) {...} :
    조건식이 true가 될 때까지만 중괄호 내부를 반복 실행한다.
  • do {...} while(조건식); :
    먼저 do 중괄호 내부를 실행하고 그다음 조건식이 true가 되면 다시 중괄호 내부를 반복 실행한다.

3. break문

for문, while문, do-while문 내부에서 실행되면 반복을 취소한다.

4. continue문

for문, while문, do-while문 내부에서 실행되면 증감식 또는 조건식으로 돌아간다.

[예제1] 입력받은 2개의 정수 비교하기

import java.util.Scanner;

public class Example1 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in); // 값 입력받음
        int pre = 0;
        int post = 0;

        while(true){ // false 조건이 없으면 무한반복!
            System.out.println("첫번째 숫자 입력 : ");
            int num1 = sc.nextInt();
            System.out.println("두번째 숫자 입력 : ");
            int num2 = sc.nextInt();

            if(num1 > num2){
                System.out.println("앞 숫자가 더 큽니다.");
                pre++;
            } else if(num1 == num2){
                System.out.println("두 숫자가 동일합니다.");
            } else{
                System.out.println("뒷 숫자가 더 큽니다.");
                post++;
            }
            System.out.println("더 하시겠습니까? 종료(x), 계속(o) >> ");
            String exit = sc.next();
            char exit2 = exit.charAt(0);
            if(exit2 == 'x'){
                System.out.println("게임을 종료합니다. ");
                System.out.println("앞 숫자가 더 큰 경우는 : " + pre + "회");
                System.out.println("뒷 숫자가 더 큰 경우는 : " + post + "회");
                System.exit(0);
            }
        }
    }

[예제2] 컴퓨터와 가위바위보 게임

import java.util.Scanner;

public class Example2 {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);

        int count = 0;
        int win = 0;

        while (true) {
            System.out.println("0이면 가위, 1이면 바위, 2이면 보");
            int com = (int) (Math.random() * 2);
            int me = s.nextInt();
            String result = "";

            if(!(me == 0 || me == 1 || me == 2)){
                System.out.println("다시 입력해주세요.");
                continue; // 반복문 재실행
            }

            System.out.println("컴퓨터: " + com + ", 나: " + me);

            if (com == me) {
                result = "무승부";
            } else if (com == 0) {
                result = me == 1 ? "내가승" : "컴퓨터승";
            } else if (com == 1) {
                result = me == 0 ? "컴퓨터승" : "내가승";
            } else if (com == 2) {
                result = me == 0 ? "내가승" : "컴퓨터승";
            }
            System.out.println(result);
            if (result == "내가승") {
                win++;
            }
            count++;

            System.out.println("종료하실래요X");
            String exit = s.next();

            char exit2 = exit.charAt(0);
            if(exit2 == 'x' || exit2 == 'X'){
                System.out.println("종료합니다.");
                break; // 반복문 탈출
            };
        }
        System.out.println("전체 "+count + "판 중에 내가 승리한 횟수는 "+win+"회");

[예제3] 인기투표

import java.util.Scanner;

public class Example3 {
    public static void main(String[] args) {

        int iu = 0;
        int you = 0;
        int bts = 0;

        Scanner sc = new Scanner(System.in);

        while(true){
            System.out.println("입력 1)아이유 2)유재석 3)방탄 4)종료 >> ");
            int choice = sc.nextInt();

            switch (choice) {
                case 1:
                    iu++;
                    break;
                case 2:
                    you++;
                    break;
                case 3:
                    bts++;
                    break;
                case 4:
                    System.out.println("종료합니다.");
                    System.out.println("아이유 득표수: " + iu);
                    System.out.println("유재석 득표수: " + you);
                    System.out.println("방탄 득표수: " + bts);
                    System.exit(0);
                default:
                    System.out.println("없는 번호입니다.");

            }
        }
    }

[예제4] 숫자 맞추기 게임

import javax.swing.*;

public class Example4 {
    public static void main(String[] args) {
        // 1~100까지의 값 랜덤하게
        int target = (int) (Math.random() * 100) + 1;
		// Random r = new Random();
		// int target = r.nextInt(100) +1; java.util.Random 클래스 이용
        System.out.println(target);
        int no = 0; // 틀린 횟수
        int count = 0; // 전체 횟수

        while (true) {
            String data = JOptionPane.showInputDialog("숫자 입력");
            int data2 = Integer.parseInt(data);
            count++;
            if (data2 == target) {
                System.out.println("정답입니다. 축하합니다.");
                break; // 반복문 탈출
            } else {
                no++;
                System.out.println("정답이 아닙니다!!");
                if (data2 > target) {
                    System.out.println("너무 커요");
                } else {
                    System.out.println("너무 작아요");
                }
            }
        }
        System.out.println("전체 시도 횟수 : " + count);
        System.out.println("틀린 횟수 : " + no);
    }

본 포스팅은 멀티캠퍼스의 멀티잇 백엔드 개발(Java)의 교육을 수강하고 작성되었습니다.

profile
성장하는 개발자, 하지은입니다.

0개의 댓글