STUDY/languages

[자바] 반복문 개념정리, 문제 모음

이앤지 2021. 11. 17. 20:24

반복문 개념

더보기
package day0909;
/*반복문
 * 반복문이란 특정 코드 블락을 조건식이 true가 나오는 동안 계속 반복하여 실행시키는
 * 특수한 코드를 반복문이라고 한다.
 * 
 * While 반복문
 * while 반복문은 if문과 구조가 비슷한데
 * if문의 경우 ()의 조건식이 true가 나오면 코드 블락을 실행시켰지만
 * while문은 ()의 조건식이 true가 나오는 '동안' 코드 블락을 실행시킨다.
 * 
 * While문의 구조
 * while(조건식) {
 *      조건식이 참일 때 실행할 코드
 * }
 * 
 */


public class Ex01While {
    public static void main(String[] args) {
        int num = 3;
        while(num <= 5) {
            System.out.println("while문 반복");
            System.out.println("num의 현재 값: "+num);
            num++;
        }
    }

}

 

문제

1.

더보기
package day0909;
/*퀴즈
 * 사용자로부터 숫자를 입력받아서 출력하는 프로그램.
 * 단 사용자가 0을 입력하면 0이 아닌 숫자가 입력될때까지
 * 다시 입력되도록 코드를 작성해보시오.
 * 
 * 제한시간 5분
 */

import java.util.Scanner;

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

//        // 내가한거,, 다시해보기 -,-;
//        Scanner sc = new Scanner(System.in);
//
//        System.out.println("숫자를 입력하세요");
//        System.out.print("> ");
//        int num = sc.nextInt();
//
//        while (num == 0) {
//
//            System.out.println("숫자를 다시 입력해주세요");
//            System.out.print("> ");
//            int num2 = sc.nextInt();
//
//        }
//        
//        System.out.println("입력한 슛자는: "+num+" 입니다");
//
//      sc.colse();
        
        
        //쌤이 한거
        Scanner scanner = new Scanner(System.in);
        
        System.out.println("숫자를 하나 입력하세요.");
        System.out.print("> ");
        int num = scanner.nextInt();
        
        while(num == 0) {
            System.out.println("0이 아닌 숫자를 입력해주세요");
            System.out.println("숫자를 하나 입력하세요.");
            System.out.print("> ");
            num = scanner.nextInt();
        }
        
        System.out.println("사용자가 입력한 숫자: "+num);
        
        scanner.close();
        
    }

}

 

2.

더보기
package day0909;
/*퀴즈, 제한시간 10분
 * 사용자로부터 점수를 입력받아
 * A, B, C, D, F가 알맞게 출력되는 프로그램을 작성하시오.
 * 단, 사용자가 잘못된 점수를 입력할 경우, 올바른 점수가 입력될 때까지
 * 다시 입력을 받도록 작성하시오.
 * 
 */

import java.util.Scanner;

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

//        //내가 한거
//        final int GRADE_A = 90;
//        final int GRADE_B = 80;
//        final int GRADE_C = 70;
//        final int GRADE_D = 60;
//
//        Scanner sc = new Scanner(System.in);
//
//        System.out.println("점수를 입력하세요");
//        System.out.print("> ");
//        int score = sc.nextInt();
//
//        while (score < 0 || score > 100) {
//            System.out.println("점수를 다시 입력하세요: ");
//            System.out.print("> ");
//            score = sc.nextInt();
//        }
//
//        if (score >= GRADE_A) {
//            System.out.println("A");
//        } else if (score >= GRADE_B && score < GRADE_A) {
//            System.out.println("B");
//        } else if (score >= GRADE_C && score < GRADE_B) {
//            System.out.println("C");
//        } else if (score >= GRADE_D && score < GRADE_C) {
//            System.out.println("D");
//        } else {
//            System.out.println("F");
//        }
//        
//        sc.close();
//        
        
        
        //쌤이 한거
        Scanner scanner = new Scanner(System.in);
        
        System.out.println("점수를 입력해주세요");
        System.out.print("> ");
        int score = scanner.nextInt();
        
        while(score < 0 || score > 100) {
            System.out.println("잘못입력하셨습니다.");
            System.out.println("점수를 입력해주세요.");
            System.out.print("> ");
            score = scanner.nextInt();
        }
        
        if(score >= 90) {
            System.out.println("A");
        } else if(score >= 80) {
            System.out.println("B");
        } else if(score >= 70) {
            System.out.println("C");
        } else if(score >= 60) {
            System.out.println("D");
        } else {
            System.out.println("F");
        }
            
        scanner.close();

    }

}

 

3.

더보기
package day0909;
/*퀴즈 제한시간 30분
 * bmi checker, gradebook
 * 
 * 사용자로부터 키와 몸무게를 입력받아
 * BMI 수치를 계산하고 비만도를 출력하는 프로그램을 작성하시오.
 * 이름: [###] 키: #.##M 몸무게: ##.##kg
 * BMI: ##.### 비만도: ###
 * 
 * 단, BMI 공식은
 * 몸무게 / 키(미터단위) / 키(미터단위) 입니다.
 * 
 * 비만도는
 * ~18.5: 저체중
 * ~23: 정상체중
 * ~25: 과체중
 * 그외: 비만
 * 으로 분류됩니다.
 * 예외
 */

/* 기네스북에 따르면 세계에서 가장 키가 컸던 사람의 키는 2.72m였습니다.
* 기네스북에 따르면 세계에서 가장 몸무게가 무거웠던 사람의 몸무게는 650킬로그램이였습니다.
* 
* 만약 사용자가 잘못된 값을 입력할 경우, 추가적인 입력 없이
* "잘못된 입력을 감지하여 프로그램을 종료합니다."라는
* 메시지가 출력되면서 프로그램이 종료되게 코드를 작성하시오.
* ---------------------------------------------------------------
*  * 사용자로부터
* 번호, 이름, 국어, 영어, 수학 점수 순으로 입력받아서
* 다음과 같은 형식으로 출력되는 프로그램을 작성하사오
* 
* 결과)
* 번호: ##번 이름:###
* 국어: 0##점 영어: 0##점 수학:0##점
* 총점: 0##점 평균: 0##.##점
* 
*  제한시간: 각 15분
*/

import java.util.Scanner;

public class Ex04Quiz {
    public static void main(String[] args) {
       
        // 내가 한거
        // bmi checker

        final double BMI_WEIGHT1 = 18.5;
        final double BMI_WEIGHT2 = 23;
        final double BMI_WEIGHT3 = 25;

        final double HEIGHT_MAX = 2.72;
        final double WEIGHT_MAX = 650;

        Scanner sc = new Scanner(System.in);

        System.out.println("이름을 입력해주세요");
        System.out.print("> ");
        sc.nextLine();
        String name = sc.nextLine();

        System.out.println("키를 미터단위로 입력해주세요");
        System.out.print("> ");
        double height = sc.nextDouble();

        System.out.println("몸무게를 키로단위로 입력해주세요");
        System.out.print("> ");
        double weight = sc.nextDouble();

        while (height > HEIGHT_MAX || height < 0 || weight > WEIGHT_MAX || weight < 0) {
            System.out.println("키를 미터단위로 다시 입력해주세요");
            System.out.print("> ");
            height = sc.nextDouble();

            System.out.println("몸무게를 키로단위로 다시 입력해주세요");
            System.out.print("> ");
            weight = sc.nextDouble();

        }
        
        double bmi = weight / height / height;
        String result;
        
        if(bmi <= BMI_WEIGHT1) {
            result = "저체중";
        } else if(bmi <= BMI_WEIGHT2) {
            result = "정상체중";
        } else if(bmi <= BMI_WEIGHT3) {
            result = "과체중";
        } else {
            result = "비만";
        }
        
        
        System.out.printf("이름: %s 키: %.2f M 몸무게: %.2f kg\n", name, height, weight);
        System.out.printf("BMI: %.3f 비만도: %s\n", bmi, result);
        
        
        sc.close();

    }

}

 

4.

더보기
package day0909;
/*퀴즈 제한시간 30분
 * bmi checker, gradebook
 * 
 * 사용자로부터 키와 몸무게를 입력받아
 * BMI 수치를 계산하고 비만도를 출력하는 프로그램을 작성하시오.
 * 이름: [###] 키: #.##M 몸무게: ##.##kg
 * BMI: ##.### 비만도: ###
 * 
 * 단, BMI 공식은
 * 몸무게 / 키(미터단위) / 키(미터단위) 입니다.
 * 
 * 비만도는
 * ~18.5: 저체중
 * ~23: 정상체중
 * ~25: 과체중
 * 그외: 비만
 * 으로 분류됩니다.
 * 예외
 */

/* 기네스북에 따르면 세계에서 가장 키가 컸던 사람의 키는 2.72m였습니다.
* 기네스북에 따르면 세계에서 가장 몸무게가 무거웠던 사람의 몸무게는 650킬로그램이였습니다.
* 
* 만약 사용자가 잘못된 값을 입력할 경우, 추가적인 입력 없이
* "잘못된 입력을 감지하여 프로그램을 종료합니다."라는
* 메시지가 출력되면서 프로그램이 종료되게 코드를 작성하시오.
* ---------------------------------------------------------------
*  * 사용자로부터
* 번호, 이름, 국어, 영어, 수학 점수 순으로 입력받아서
* 다음과 같은 형식으로 출력되는 프로그램을 작성하사오
* 
* 결과)
* 번호: ##번 이름:###
* 국어: 0##점 영어: 0##점 수학:0##점
* 총점: 0##점 평균: 0##.##점
* 
*  제한시간: 각 15분
*/

import java.util.Scanner;

public class Ex05QuizAnswer {
    public static void main(String[] args) {
        
//        //쌤이 한거
//        //1. BMI CHECKER        
//        Scanner scanner = new Scanner(System.in);
//        // 상수
//        final double MAX_HEIGHT = 2.72;
//        final double MAX_WEIGHT = 650;
//        final double BMI_STANDARD1 = 18.5;
//        final double BMI_STANDARD2 = 23;
//        final double BMI_STANDARD3 = 25;
//        
//        System.out.println("이름을 입력해주세요");
//        System.out.print("> ");
//        scanner.nextLine();
//        String name = scanner.nextLine();
//
//        // 키 입력받기->몸무게 입력받기->BMI계산->결과값결정->출력
//        System.out.println("키를 입력해주세요.");
//        System.out.print("> ");
//        double height = scanner.nextDouble();
//
//        while (!(height > 0 && height <= MAX_HEIGHT)) { //!를 써서 아니라는거를 더 명확하게 표현
//            System.out.println("잘못 입력하셨습니다.");
//
//            System.out.println("키를 입력해주세요.");
//            System.out.print("> ");
//            height = scanner.nextDouble();
//
//        }
//        
//        System.out.println("몸무게를 입력해주세요.");
//        System.out.print("> ");
//        double weight = scanner.nextDouble();
//
//        while (!(weight > 0 && weight <= MAX_WEIGHT)) {
//            System.out.println("잘못 입력하셨습니다.");
//
//            System.out.println("몸무게를 입력해주세요.");
//            System.out.print("> ");
//            weight = scanner.nextDouble();
//
//        }
//        
//        double bmi = weight / height / height;        
//        String result = "비만"; //기본값, else로 별도지정안해줘도 됨!, 기본값&else 두가지다 가능한 방법임!
//        
//        if(bmi < BMI_STANDARD1) {
//            result = "저체중";
//        } else if(bmi < BMI_STANDARD2) {
//            result = "정상체중";
//        } else if(bmi < BMI_STANDARD3) {
//            result = "과체중";
//        }
//
//        System.out.printf("이름: %s 키: %.2f M 몸무게: %.2f kg\n", name, height, weight);
//        System.out.printf("BMI: %.3f 비만도: %s\n", bmi, result);
//        
//
//        scanner.close();

        
        
        
//      //쌤이 한거
//      //2. GradeBook
        Scanner scanner = new Scanner(System.in);
        //상수
        final int SUBJECT_SIZE = 3; //과목개수 숫자
        
        //사용자가 입력한 int값을 임시로 보관할 변수
        int temp;
        
        //번호입력->이름입력->국어,영어,수학점수 입력->총점 계산, 평균계산, 결과 출력
        System.out.println("번호를 입력해주세요.");
        System.out.print("> ");
        int id = scanner.nextInt();
        
        System.out.println("이름을 입력해주세요.");
        System.out.print("> ");
        scanner.nextLine();
        String name = scanner.nextLine();
        
        System.out.println("국어 점수를 입력해주세요.");
        System.out.print("> ");
        temp = scanner.nextInt();
        
        while( !(temp>=0 && temp <= 100)) {
            System.out.println("잘못 입력하셨습니다.");

            System.out.println("국어 점수를 입력해주세요.");
            System.out.print("> ");
            temp = scanner.nextInt();
        }               
        int korean = temp;
        
        
        System.out.println("영어 점수를 입력해주세요.");
        System.out.print("> ");
        temp = scanner.nextInt();
        
        while( !(temp>=0 && temp <= 100)) {
            System.out.println("잘못 입력하셨습니다.");
            
            System.out.println("영어 점수를 입력해주세요.");
            System.out.print("> ");
            temp = scanner.nextInt();
        }
        int english = temp;
        
        
        System.out.println("수학 점수를 입력해주세요.");
        System.out.print("> ");
        temp = scanner.nextInt();
        
        while( !(temp>=0 && temp <= 100)) {
            System.out.println("잘못 입력하셨습니다.");
            
            System.out.println("수학 점수를 입력해주세요.");
            System.out.print("> ");
            temp = scanner.nextInt();
        }
        int math = temp;
        
        
        int sum = korean + english + math;
        
        double average = (double)sum / SUBJECT_SIZE;
        
        //결과출력
        System.out.printf("번호: [%d]번  이름: [%s]\n ", id, name);
        System.out.printf("국어: [%03d]점 영어: [%03d]점 수학: [%03d]점\n", korean, english, math);        
        System.out.printf("총점: [%03d]점 평균: [%06.2f]점\n", sum, average);
        

        scanner.close();
        
    }

}

 

무한루프 개념

더보기
package day0909;
/*무한 루프(Infinite Loop)
 * 무한 루프란, 반복문의 조건식의 결과값이 무조건 true가 나와서
 * 우리가 강제로 종료시키기 전까지는
 * 영원히 반복되는 반복문을 무한 루프라고 부른다.
 * 
 * 무한 루프를 만드는 방법은 다양하지만
 * 우리는 while문을 사용한 무한루프를 만드는 3가지 방법을 알아볼 것이다.
 */

public class Ex06InfiniteLoop {
    public static void main(String[] args) {
        /*무한 루프 1번
         * 조건식의 결과값이 true가 나오는
         * 변화없는 변수를 써보자
         */
//        int num = 3;
//        while(num < 5) {
//            System.out.println("무한루프 1번");
//            System.out.println("변화없는 변수");
//        }
        
        
        /*무한 루프 2번
         * 변수 없이 항상 true가 나오는 조건식
         */
//        while(0 < 1) {
//            System.out.println("무한루프 2번");
//            System.out.println("항상 true가 나오는 조건식");
//        }
        
        
        /*무한 루프 3번
         * true
         */
        while(true) {
            System.out.println("무한루프 3번");
        }
        
    }

}

 

 

문제 5. 

더보기
package day0909;
/*퀴즈
 * 사용자로부터 점수를 입력받아
 * A, B, C, D, F를 출력하는 프로그램
 * 단, 사용자가 입력을 누르면 입력기능이 실행되고
 * 출력 기능을 실행하면 가장 마지막에 입력한 점수와 알파벳이 출력된다.
 * 또한 잘못된 점수를 입력했을 경우, 올바른 점수가 입력될때까지 다시 입력을 받는다.
 * 
 * 제한시간 25분
 * 힌트) 변수의 유효범위!
 */

import java.util.Scanner;

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

//        // 내가 한거,, ㅠㅠ 실패,,,
//        Scanner sc = new Scanner(System.in);
//
//        System.out.println("입력은 1, 출력은 2를 눌러주세요");
//        System.out.print("> ");
//        int userChoice = sc.nextInt();
//
//        String result;
//        int score1;
//        
//        if (userChoice == 1) {
//            System.out.println("점수를 입력해주세요.");
//            System.out.print("> ");
//            int score = sc.nextInt();
//            
//            if(score >= 90) {
//                result = "A";
//            } else if(score >= 80) {
//                result = "B";
//            } else if(score >= 70) {
//                result = "C";
//            } else if(score >= 60) {
//                result = "D";
//            } else {
//                result = "E";
//            }
//            
//            score = score1;
//            
//            System.out.println("출력을 원하시면 2번을 눌러주세요.");
//
//        } else if(userChoice == 2) {
//            System.out.printf("점수: %d, 등급: %s", score1, result);
// 
//        }
//        
//
//        while (!(userChoice == 1 || userChoice == 2)) {
//            System.out.println("잘못된 입력입니다.");
//
//            System.out.println("점수를 다시 입력해주세요.");
//            System.out.print("> ");
//            userChoice = sc.nextInt();
//        }
//        
//        sc.close();
        
        
        
        //쌤이 한거
        Scanner scanner = new Scanner(System.in);
        
        int score = 0; //변수의 유효범위!!!!!!!
        
        while(true) {
            System.out.println("1.입력  2.출력  3.종료");
            System.out.print("> ");
            int userChoice = scanner.nextInt();
            
            if(userChoice == 1) {
                //입력 코드 구현
                System.out.println("점수를 입력해주세요.");
                System.out.print("> ");

                while( !(score >= 0 && score <= 100)) {
                    System.out.println("잘못 입력하셨습니다.");
                    System.out.println("점수를 다시 입력해주세요.");
                    System.out.print("> ");
                    
                    score = scanner.nextInt();
                    
                }
                
                
            } else if(userChoice == 2) {
                //출력 코드 구현
                if(score >= 90) {
                    System.out.println("A");
                } else if(score >= 80) {
                    System.out.println("B");
                } else if(score >= 70) {
                    System.out.println("C");
                } else if(score >= 60) {
                    System.out.println("D");
                } else {
                    System.out.println("F");
                }
                
                
            } else if(userChoice == 3) {
                //메시지 출력 후 break;
                System.out.println("사용해주셔서 감사합니다.");
                break;
            }
            
        }
        
        
        scanner.close();
        
        
    }

}

 

랜덤 클래스

더보기
package day0909;
/*Random 클래스
 * Random 은 정해진 규칙 없이 무수히 많은 숫자들이
 * 나열되어있고 그것을 우리가 하나씩 뽑는 개념인
 * 난수를 담당하는 클래스로써,
 * 우리가 랜덤한 숫자를 뽑을 수 있게 해준다.
 * Scanner와 마찬가지로, java.util에 있는
 * Random 클래스를 우리가 불러와야 정상적으로 사용을 할 수 있다.
 */

import java.util.Random;

public class Ex11Random {
    public static void main(String[] args) {
        Random random = new Random();
        
        /* random은 내부적으로
         * 0부터 1사이의 무수한 실수를 뒤죽박죽 순서로 가지고 있다
         * 우리가 요청할 때마다 그 실수를 하나씩 꺼내주는 개념이다.
         * 
         * 만약 우리가 실수 데이터타입의 난수가 필요할 때에는
         * nextDouble() 메소드를 사용하면 된다.
         */
        System.out.println("1. nextDouble");
        System.out.println("1: "+ random.nextDouble());
        System.out.println("2: "+ random.nextDouble());
        System.out.println("3: "+ random.nextDouble());
        System.out.println("4: "+ random.nextDouble());
        System.out.println("5: "+ random.nextDouble());

        System.out.println("---------------------\n");
        
        
        /* 만약 int타입의 난수가 필요할 경우
         * nextInt() 메소드를 사용하면 된다.
         * 이 때에는 int 범위 전체가 난수의 범위가 된다.
         */
        System.out.println("2. nextInt");
        System.out.println("1: "+ random.nextInt());
        System.out.println("2: "+ random.nextInt());
        System.out.println("3: "+ random.nextInt());
        System.out.println("4: "+ random.nextInt());
        System.out.println("5: "+ random.nextInt());

        System.out.println("---------------------\n");
        
        
        /* 만약 우리가 0부터 특정 범위의 값이 필요한 경우
         * nextInt(최댓값) 메소드를 사용하면 된다.
         * 이 때에는 0부터 최대값-1 까지의 값이
         * 난수의 범위가 된다.
         */
        System.out.println("3. nextInt(MAX)");
        System.out.println("1: "+ random.nextInt(3)); //범위 0~2
        System.out.println("2: "+ random.nextInt(3));
        System.out.println("3: "+ random.nextInt(3));
        System.out.println("4: "+ random.nextInt(3));
        System.out.println("5: "+ random.nextInt(3));

        System.out.println("---------------------\n");
        
        
        /* 그렇다면 만약 우리가 0부터 특정값-1 이 아닌
         * 1부터 특정값까지의 난수가 필요할 때에는
         * 어떻게 해야 할까?
         */
        System.out.println("4. nextInt(MAX)");
        System.out.println("1: "+ (random.nextInt(3)+1 )); //범위 1~2
        System.out.println("2: "+ (random.nextInt(3)+1 ));
        System.out.println("3: "+ (random.nextInt(3)+1 ));
        System.out.println("4: "+ (random.nextInt(3)+1 ));
        System.out.println("5: "+ (random.nextInt(3)+1 ));

        System.out.println("---------------------\n");
        
        
        
    }

}

 

문제 6.

더보기
package day0909;
/*랜덤 게임
 * 제한시간 30분
 * 
 * 컴퓨터가 만든 1~100 사이의 숫자를
 * 사용자가 맞추는 게임
 * 플레이, 최고 점수 보기, 종료 기능이 있다.
 * 
 * 플레이를 할 시에는
 * 컴퓨터가 숫자를 하나 뽑아 놓고
 * 사용자는 그 숫자를 맞출 때 까지 입력을 하게 된다.
 * 사용자는 최초 입력을 포함하여
 * 입력을 할 떄마다 1씩 점수가 오르게 된다.
 * 만약 필요한 경우, 기존 최고 점수를 현재 점수로 갱신하는 기능도 있어야 한다.
 * 
 * 최고 점수 보기
 * 최고 점수 보기의 경우, 현재 최고 점수를 보여주는데
 * 게임의 특성상 입력 횟수가 낮을 수록 높은 점수가 된다.
 * 또한 만약 사용자가 플레이한 기록이 없을 시에는
 * "아직 플레이 기록이 없습니다!"라고 출력이 되게 한다.
 */

import java.util.Scanner;
import java.util.Random;

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

//        //내가한거,, 도전수=난수 확인은 못해봤음
//        Scanner scanner = new Scanner(System.in);
//        Random random = new Random();
//
//        int num = 0;
//        int up = 0;
//
//        int rdNum = random.nextInt(100) + 1;
//
//        boolean inputSwitch = false;
//
//        while (true) {
//            System.out.println("1.플레이  2.최고 점수 보기  3.종료");
//            System.out.println("> ");
//            int userChoice = scanner.nextInt();
//
//            if (userChoice == 1) {
//                int temp;
//
//                System.out.println("도전할 숫자를 입력해주세요.");
//                System.out.print("> ");
//                temp = scanner.nextInt();
//
//                while (!(temp >= 0 && temp <= 100)) {
//                    System.out.println("잘못 입력하셨습니다.");
//
//                    System.out.println("도전할 숫자를 재입력해주세요.");
//                    System.out.print("> ");
//                    temp = scanner.nextInt();
//
//                }
//
//                System.out.println("숫자: " + (rdNum));
//                if (temp == rdNum) {
//                    System.out.println("정답입니다! " + (rdNum) + temp);
//
//                    up += 1;
//
//                } else if (temp != rdNum) {
//                    System.out.println("실패! 재도전하세요! 난수:" + (rdNum) + " 나의 수:" + temp);
//                }
//                num = temp;
//
//                // 심화문제 풀이
//                inputSwitch = true;
//
//            } else if (userChoice == 2) {
//                if (inputSwitch) {
//                    System.out.println("최고점수입니다: " + up); // 범위 0~2
//
//                }
//
//                else {
//                    System.out.println("아직 입력된 정보가 존재하지 않습니다.");
//                }
//
//            } else if (userChoice == 3) {
//                // 종료
//                System.out.println("사용해주셔서 감사합니다.");
//                break;
//
//            }
//        }
//
//        scanner.close();

        
        
        
        
        // 쌤이 한거
//        Scanner scanner = new Scanner(System.in);
//        Random random = new Random();
//
//        //가능한 최솟값
//        //final int MIN = 1;
//        //가능한 최댓값
//        final int MAX = 10;
//
//        int bestScore = 0;
//
//        while (true) {
//            System.out.println("1.플레이 2.최고기록보기 3.종료");
//            System.out.print("> ");
//            int userChoice = scanner.nextInt();
//
//            if (userChoice == 1) {
//                
//                //1. 컴퓨터 숫자 지정
//                int computerNum = random.nextInt(MAX)+1;
//                
//                //2. 사용자의 현재 점수를 저장할 변수 선언 및 초기화
//                int currentScore = 1; //
//                
//                //3. 사용자로부터 숫자 입력 받기
//                System.out.println("숫자를 입력해주세요.");
//                System.out.println("> ");
//                int userNum = scanner.nextInt();
//                
//                while(userNum != computerNum) {
//                    System.out.println("틀렸습니다. "+computerNum);
//                    System.out.println("숫자를 입력해주세요.");
//                    System.out.println("> ");
//                    userNum = scanner.nextInt();
//                    currentScore++;
//                }
//                
//                //4. 현재 점수를 토대로 해서 결과 결정 및 보여주기
//                System.out.println("이번 플레이 기록: " + currentScore);
//                if(bestScore == 0 || currentScore < bestScore) {
//                    System.out.println("짝짝짝 새로운 기록입니다!");
//                }
//                
//
//            } else if (userChoice == 2) {
//                if(bestScore != 0) {
//                    System.out.printf("현재 최고 기록: %d회 \b", bestScore);
//                } else {
//                    System.out.println();
//                    System.out.println("아직 플레이 기록이 없습니다.");
//                    System.out.println();
//                }
//
//            } else if (userChoice == 3) {
//                System.out.println("플레이 해주셔서 가사합니다.");
//                break;
//            }
//        }
//        
//        scanner.close();

        
        Scanner scanner = new Scanner(System.in);
        Random random = new Random();
        // 상수
        // 가능한 최소 값
        //final int MIN = 1;
        // 가능한 최대 값
        final int MAX = 100;
        
        int bestScore = 0;
        
        while(true) {
            System.out.println("1. 플레이 2. 최고 기록 보기 3. 종료");
            System.out.print("> ");
            int userChoice = scanner.nextInt();
            
            if(userChoice == 1) {
                
                // 1. 컴퓨터 숫자 지정
                int computerNum = random.nextInt(MAX) + 1;
                
                // 2. 사용자의 현재 점수를 저장할 변수 선언 및 초기화
                int currentScore = 1;
                
                // 3. 사용자로부터 숫자 입력 받기
                System.out.println("숫자를 입력해주세요.");
                System.out.print("> ");
                int userNum = scanner.nextInt();
                
                while(userNum != computerNum) {
                    System.out.println("틀렸습니다."+computerNum);
                    System.out.println("숫자를 입력해주세요.");
                    System.out.print("> ");
                    userNum = scanner.nextInt();
                    currentScore++;
                }
                
                // 4. 현재 점수를 토대로 해서 결과 결정 및 보여주기
                
                System.out.println("이번 플레이 기록: " + currentScore);
                
                if(bestScore == 0 || currentScore < bestScore) {
                    bestScore = currentScore;
                    System.out.println("짝짝작 새로운 기록입니다!");
                }
                
                
                // 플레이 코드 마지막 줄
            } else if(userChoice == 2) {
                
                if(bestScore != 0) {
                    
                    System.out.printf("현재 최고 기록: [%d]회\n", bestScore);
                    
                } else {
                    
                    System.out.println();
                    System.out.println("아직 플레이 기록이 없습니다.");
                    System.out.println();
                    
                }
                
                // 기록 보기 코드 마지막 줄
            } else if(userChoice == 3) {
                System.out.println("플레이해주셔서 감사합니다.");
                break;
                // 종료 코드 마지막 줄
            }
            
        }
        
        
        scanner.close();
        
        
    }
}

 

문제 7.

더보기
package day0909;

/*
 *
숙제1. 우리가 만든 숫자 맞추기 게임에서
사용자가 컴퓨터 숫자보다 큰 값을 입력하면 DOWN,
작은 값을 입력하면 UP 이 출력되게 프로그램을 업그레이드 하시오
 
숙제2.
가위바위보 게임을 만드세요
1. 플레이 하기
사용자가 선택한 것과
컴퓨터가 선택한 것을 
각각 보여주고
승리, 무승부, 패배 중 하나를 결과로 출력합니다.

2. 결과 보기
사용자의 승리, 무승부, 패배 그리고 승률을 출력합니다.
단, 사용자가 한번도 하지 않은 경우에는 
아직 플레이 기록이 없습니다 가 출력됩니다.

 */

import java.util.Scanner;
import java.util.Random;

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

        // 숙제1.
//        Scanner scanner = new Scanner(System.in);
//        Random random = new Random();
//
//        final int MAX = 100;
//
//        int bestScore = 0;
//
//        while (true) {
//            System.out.println("1. 플레이 2. 최고 기록 보기 3. 종료");
//            System.out.print("> ");
//            int userChoice = scanner.nextInt();
//
//            if (userChoice == 1) {
//
//                int computerNum = random.nextInt(MAX) + 1;
//
//                int currentScore = 1;
//
//                System.out.println("\n숫자를 입력해주세요.");
//                System.out.print("> ");
//                int userNum = scanner.nextInt();
//
//                while (userNum != computerNum) {
//                    System.out.println("틀렸습니다." + computerNum);
//
//                    if (userNum > computerNum) {
//                        System.out.println("더 작은 숫자를 입력해보세요\n");
//                    } else if (userNum < computerNum) {
//                        System.out.println("더 큰 숫자를 입력해보세요\n");
//                    }
//
//                    System.out.println("숫자를 입력해주세요.");
//                    System.out.print("> ");
//                    userNum = scanner.nextInt();
//                    currentScore++;
//
//                }
//
//                System.out.println("이번 플레이 기록: " + currentScore);
//
//                if (bestScore == 0 || currentScore < bestScore) {
//                    bestScore = currentScore;
//                    System.out.println("짝짝작 새로운 기록입니다!\n\n");
//                }
//
//            } else if (userChoice == 2) {
//
//                if (bestScore != 0) {
//
//                    System.out.printf("\n현재 최고 기록: [%d]회\n\n", bestScore);
//
//                } else {
//
//                    System.out.println();
//                    System.out.println("아직 플레이 기록이 없습니다.");
//                    System.out.println();
//
//                }
//
//            } else if (userChoice == 3) {
//                System.out.println("플레이해주셔서 감사합니다.");
//                break;
//            }
//
//        }
//
//        scanner.close();

        // 숙제2.
        Scanner scanner = new Scanner(System.in);
        Random random = new Random();

        final int MAX = 3;

        int bestScore = 0;
        int currentScore = 1;
        
        int win = 1;
        int draw = 1;
        int lose = 1;
        
        //승률
        double per = win/currentScore;

        //계속하시겠습니까
        int go = 0;
        
        while (true) {
            System.out.println("1. 플레이 2. 최고 기록 보기 3. 종료");
            System.out.print("> ");
            int userChoice = scanner.nextInt();

            if (userChoice == 1) {

                int comNum = random.nextInt(MAX) + 1;

                System.out.println("선택 하세요!");
                System.out.println("1.가위 2.바위 3.보 \n");
                System.out.print("> ");
                int userNum = scanner.nextInt();
                
                System.out.println("계속하시려면 1번을 눌러주세요> ");
                go = scanner.nextInt();

                while(go == 1) {
                   if (userNum == 1) {
                        if (comNum == 2) {
                            System.out.println("당신: 1.가위 vs 컴퓨터 2.바위");
                            System.out.println("졌습니다!\n");
                            lose++;
                        } else if (comNum == 3) {
                            System.out.println("당신: 1.가위 vs 컴퓨터 3.보");
                            System.out.println("이겼습니다!\n");
                            win++;
                        }
                    }
                    if (userNum == 2) {
                        if (comNum == 1) {
                            System.out.println("\n당신: 2.바위 vs 컴퓨터 1.가위");
                            System.out.println("이겼습니다!\n");
                            win++;
                        }else if (comNum == 3) {
                            System.out.println("당신: 2.바위 vs 컴퓨터 3.보");
                            System.out.println("졌습니다!\n");
                            lose++;
                        }
                    }
                    if (userNum == 3) {
                        if (comNum == 1) {
                            System.out.println("\n당신: 3.보 vs 컴퓨터 1.가위");
                            System.out.println("졌습니다!\n");
                            lose++;
                        } else if (comNum == 2) {
                            System.out.println("당신: 3.보 vs 컴퓨터 2.바위");
                            System.out.println("이겼습니다!\n");
                            win++;
                        }
                    }
                    
                    if (comNum == 1) {
                        System.out.println("\n당신: 1.가위 vs 컴퓨터 1.가위");
                        System.out.println("비겼습니다!\n");
                        draw++;
                    } else if (comNum == 2) {
                        System.out.println("당신: 2.바위 vs 컴퓨터 2.바위");
                        System.out.println("비겼습니다!\n");
                        draw++;
                    } else if (comNum == 3) {
                        System.out.println("당신: 3.보 vs 컴퓨터 3.보");
                        System.out.println("비겼습니다!\n");
                        draw++;
                    }
                    
                    System.out.println("계속하시려면 1번을 눌러주세요> ");
                    go = scanner.nextInt();
                    System.out.println("끝내시려면 2번을 눌러주세요> ");
                    if(go==2) {
                    break;
                    }
                    
                }
                                     
                    currentScore++;

                System.out.println("이번 플레이 기록: " + currentScore);

                if (bestScore == 0 || currentScore < bestScore) {
                    bestScore = currentScore;
                    System.out.println("짝짝작 새로운 기록입니다!\n\n");
                }

            } else if (userChoice == 2) {

                if (bestScore != 0) {

                    System.out.printf("\n현재 최고 기록: [%d]회\n", bestScore);
                    
                    System.out.printf("승리:%d, 무승부:%d, 패배:%d \n승률: %f%%\n",win,draw,lose,per);
                    

                } else {

                    System.out.println();
                    System.out.println("아직 플레이 기록이 없습니다.");
                    System.out.println();

                }

            } else if (userChoice == 3) {
                System.out.println("플레이해주셔서 감사합니다.");
                break;
            }

        }

    scanner.close();

}

}
    
    
    
    
    
///////////////////////////////////////////////////////////////////////////////////////////////////////////
//다른 사람들이 한거
//package day0909;
//
//import java.util.Random;
//import java.util.Scanner;
//
//public class Ex13Random_3 {
//
//    public static void main(String[] args) {
//        Scanner scanner = new Scanner(System.in);
//        Random random = new Random();
//        
//        int victory = 0;
//        int draw = 0;
//        int defeat = 0;
//        int total=0;
//        
//        
//        while(true) {
//            System.out.println("1. 플레이하기 2. 결과보기");
//            System.out.print("> ");
//            
//            int userChoice = scanner.nextInt();
//            
//            
//            
//            if(userChoice == 1) {
//                 // 1. 컴퓨터 숫자 지정
//                int computerNum = random.nextInt(10) %3;
//                
//                // 2. 사용자의 현재 점수를 저장할 변수 선언 및 초기화
//                
//             // 3. 사용자로부터 숫자 입력 받기
//                System.out.println("가위 1 바위 2 보 3 선택하세요.");
//                System.out.print("> ");
//                int userNum = scanner.nextInt();
//                
//                if (userNum == 1 && computerNum == 0) {
//                    System.out.println("유저 가위 컴퓨터 가위 무승부.");
//                    draw++;
//                    total++;
//                }
//                else if (userNum == 1 && computerNum == 1) {
//                    System.out.println("유저 가위 컴퓨터 바위 패배.");
//                    defeat++;
//                    total++;
//                    
//                }
//                else if (userNum == 1 && computerNum == 2) {
//                    System.out.println("유저 가위 컴퓨터 보 승리.");
//                    victory++;
//                    total++;
//                }
//                else if (userNum == 2 && computerNum == 0) {
//                    System.out.println("유저 바위 컴퓨터 가위 승리.");
//                    victory++;
//                    total++;
//                }
//                else if (userNum == 2 && computerNum == 1) {
//                    System.out.println("유저 바위 컴퓨터 바위 무승부.");
//                    draw++;
//                    total++;
//                }
//                else if (userNum == 2 && computerNum == 2) {
//                    System.out.println("유저 바위 컴퓨터 보 패배.");
//                    defeat++;
//                    total++;
//                }
//                else if (userNum == 3 && computerNum == 0) {
//                    System.out.println("유저 보 컴퓨터 가위 패배.");
//                    defeat++;
//                    total++;
//                }
//                else if (userNum == 3 && computerNum == 1) {
//                    System.out.println("유저 보 컴퓨터 바위 무승부.");
//                    draw++;
//                    total++;
//                }
//                else if (userNum == 3 && computerNum == 2) {
//                    System.out.println("유저 보 컴퓨터 보 승리.");
//                    victory++;
//                    total++;
//                }
//                
//                
//                
//            }
//            
//            if(userChoice == 2) {
//                if (total==0) {
//                    System.out.println("아직 플레이 기록이 없습니다");
//                    continue;
//                }
//                System.out.printf("승리: %d 무승부: %d 패배 : %d 승률 : %f" , victory,draw,defeat,(double)victory/total);
//                System.out.println("\n");
//                
//                
//            }
//            
//            
//            
//        }
//        
//        
//        
//        
//        
//    }
//}


//package day0909;
//랜덤 게임
//컴퓨터가 만든 1~100 사이의 숫자를 
//사용자가 맞추는 게임
//플레이, 최고 점수 보기, 종료 기능이 있다.

//플레이를 할 시에는 
//컴퓨터가 숫자를 하나 뽑아 놓고
//사용자는 그 숫자를 맞출 때 까지 입력을 하게 된다.
//사용자는 최초 입력을 포함하여
//입력을 할 때마다 1씩 점수가 오르게 된다.
//만약 필요한 경우, 기존 최고 점수를 현재 점수로 갱신하는 기능도 있어야 한다.

//최고 점수 보기
//최고 점수 보기의 경우, 현재 최고 점수를 보여주는데
//게임의 특성상 입력 횟수가 낮을 수록 높은 점수가 된다.
//또한 만약 사용자가 플레이한 기록이 없을 시에는
//"아직 플레이 기록이 없습니다!" 라고 출력이 되게 된다.

//import java.util.Scanner;
//import java.util.Random;
//public class Ex12RandomGame {
// public static void main(String[] args) {
//     Scanner scanner = new Scanner(System.in);
//     Random random = new Random();
//     // 상수
//     // 가능한 최소 값
//     final int MIN = 1;
//     // 가능한 최대 값
//     final int MAX = 100;
//     
//     int bestScore = 0;
//     
//     while(true) {
//         System.out.println("1. 플레이 2. 최고 기록 보기 3. 종료");
//         System.out.print("> ");
//         int userChoice = scanner.nextInt();
//         
//         if(userChoice == 1) {
//             
//             // 1. 컴퓨터 숫자 지정
//             int computerNum = random.nextInt(MAX) + 1;
//             
//             // 2. 사용자의 현재 점수를 저장할 변수 선언 및 초기화
//             int currentScore = 1;
//             
//             // 3. 사용자로부터 숫자 입력 받기
//             System.out.println("숫자를 입력해주세요.");
//             System.out.print("> ");
//             int userNum = scanner.nextInt();
//             
//             while(userNum != computerNum) {
//                 //@System.out.println("틀렸습니다.");
//                 if(userNum > computerNum) {
//                     System.out.print("DOWN");
//                     
//                     
//                 } else {
//                     System.out.println("UP");
//                     
//                     
//                     
//                 }
//                 
//                 
//                 
//                 System.out.println("숫자를 입력해주세요.");
//                 System.out.print("> ");
//                 userNum = scanner.nextInt();
//                 currentScore++;
//             }
//             
//             // 4. 현재 점수를 토대로 해서 결과 결정 및 보여주기
//             
//             System.out.println("이번 플레이 기록: " + currentScore);
//             
//             if(bestScore == 0 || currentScore < bestScore) {
//                 bestScore = currentScore;
//                 System.out.println("짝짝작 새로운 기록입니다!");
//             }
//             
//             
//             // 플레이 코드 마지막 줄
//         } else if(userChoice == 2) {
//             
//             if(bestScore != 0) {
//                 
//                 System.out.printf("현재 최고 기록: [%d]회\n", bestScore);
//                 //@System.out.println("현재 최고 기록 : ["+bestScore+"]회");
//             } else {
//                 
//                 System.out.println();
//                 System.out.println("아직 플레이 기록이 없습니다.");
//                 System.out.println();
//                 
//             }
//             
//             // 기록 보기 코드 마지막 줄
//         } else if(userChoice == 3) {
//             System.out.println("플레이해주셔서 감사합니다.");
//             break;
//             // 종료 코드 마지막 줄
//         }
//         
//     }
//     
//     
//     scanner.close();
// }
//}

더보기
package day0909;

import java.util.Scanner;
import java.util.Random;

public class Ex14HwAnwer {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        Random random = new Random();

        // 고정 값은 상수로 정해주는게 좋음!
        final int OPTION_SCISSOR = 1; // 기위
        final int OPTION_ROCK = 2; // 바위
        final int OPTION_PAPER = 3; // 보

        // 최대 선택 가능한 옵션 숫자
        final int OPTION_MAX = 3;

        // 변수
        int win = 0; // 승리
        int draw = 0;// 무승부
        int lose = 0;// 패배

        while (true) {
            System.out.println("1. 플레이 2. 최고 기록 보기 3. 종료");
            System.out.print("> ");
            int userChoice = scanner.nextInt();

            if (userChoice == 1) {
                // 플레이 코드구현 시작

                // 1. 컴퓨터 숫자 결정
                int computerNum = random.nextInt(OPTION_MAX) + 1;

                // 2. 사용자 숫자 결정
                System.out.println("1.가위 2.바위 3.보");
                System.out.println("> ");
                int userNum = scanner.nextInt();

                // 사용자가 이상한거 눌렀을 떄 예외처리
                while (!(userNum >= OPTION_SCISSOR && userNum <= OPTION_PAPER)) {
                    System.out.println("잘못 입력하셨습니다.");
                    System.out.println("1.가위 2.바위 3.보");
                    System.out.println("> ");
                    userNum = scanner.nextInt();
                }

                // 3. 결과계산 및 출력

                // 승리, 무승부, 패배 중 하나를 저장할 String result
                String result = "";

                // 컴퓨터의 선택을 "가위 바위 보"중 하나로 변환해서 저장할 String compChoice;
                String comText = "";

                // 사용자의 선택을 "가위 바위 보"중 하나로 변환해서 저장할 String userText;
                String userText = "";

                // 무승부인가 아닌가
                if (userNum == computerNum) {
                    // 무승부인 경우
                    result = "무승부";
                    draw++;

                    if (userNum == OPTION_SCISSOR) {
                        userText = comText = "가위";
                    } else if (userNum == OPTION_ROCK) {
                        userText = comText = "바위";
                    } else if (userNum == OPTION_PAPER) {
                        userText = comText = "보";
                    }
                } else {
                    // 무승부가 아닌경우
                    if (userNum == OPTION_SCISSOR) {
                        userText = "가위";
                        if (computerNum == OPTION_ROCK) {
                            comText = "바위";
                            lose++;
                            result = "패배";

                        } else if (computerNum == OPTION_PAPER) {
                            comText = "보";
                            win++;
                            result = "승리";
                        }

                    } else if (userNum == OPTION_ROCK) {
                        userText = "바위";
                        if (computerNum == OPTION_SCISSOR) {
                            comText = "가위";
                            win++;
                            result = "승리";
                        } else if (computerNum == OPTION_PAPER) {
                            comText = "보";
                            lose++;
                            result = "패배";
                        }

                    } else if (userNum == OPTION_PAPER) {
                        userText = "보";
                        if (computerNum == OPTION_SCISSOR) {
                            comText = "가위";
                            lose++;
                            result = "패배";
                        } else if (computerNum == OPTION_ROCK) {
                            comText = "바위";
                            win++;
                            result = "승리";
                        }

                    }

                }

                // 출력
                System.out.printf("컴퓨터:%s 사용자:%s 결과:%s \n", comText, userText, result);

                // 플레이 코드구현 끝
            } else if (userChoice == 2) {
                // 기록보기 코드구현 시작

                // 총 전적을 계산한다.
                int total = win + draw + lose;

                if (total > 0) {
                    // 사용자가 한번이라도 플레이 했으므로
                    // 전적을 출력한다.
                    double rate = (double) win / total * 100;

                    System.out.printf("\n승리:[%d]회 무승부:[%d]회 패배:[%d]회 승률:[%.2f]%% \n\n", win, draw, lose, rate);

                } else {
                    // 사용자가 한번도 플레이 한 적 없으므로
                    // 메시지만 출력한다.
                    System.out.println("\n 아직 플레이 기록이 없습니다.\n");
                }

                // 기록코드 코드구현 끝

            } else if (userChoice == 3) {
                // 종료코드 구현시작
                System.out.println("플레이 해주셔서 감사합니다.");
                break;
                // 종료코드 구현 끝
            }
        }

        scanner.close();

    }

}

 


for 문

더보기
package day0910;
/*반목문
 * for 반복문
 * while 반복문은 횟수에 딱히 구속적인 느낌이 아니지만
 * 그에 반해 for문은 비교적 횟수가 명확하게 지정된 반복문이다.
 * 
 * for 반복문은 다음과 같은 구조를 가진다.
 * for(제어변수의 선언과 초기화; 반복 조건식; 반복 후 제어변수의 변화식){
 *      반복할 코드
 * }
 */


public class Ex01For {
    public static void main(String[] args) {
        //1. 기본적인 for문
        System.out.println("1. 기본for문");
        
        for(int i=1; i<=3; i++) { //유효범위 잘 생각하기!
            System.out.println("i의 현재값: "+i); 
        }
        
        System.out.println("---------------------\n");
        
        
        /*2. 제어변수 이름
         * 전통적으로 for문의 제어변수는 i로 시작하여
         * 중첩되는 레벨에 따라 j, k 순으로 들어가지만
         * 만약 익숙하지 않을 때에는 다른 이름을 사용하더라도
         * 상관 없다.
         */
        System.out.println("2. 제어변수 이름");
        for(int num = 1; num <= 4; num++) {
            System.out.println("num의 현재값: "+num);            
        }
        System.out.println("---------------------\n");
        
        
        /*3. 우리가 지금은 제어변수의 변화식을 ++을 썼지만
         * 제어변수 안의 값을 변화시킬 수 있는 연산자 혹은 메소드는 뭐든 가능하다. 
         */
        System.out.println("3. 제어변수의 변화식");
        for(int i = 1; i <= 100000; i *= 100) {
            System.out.println("i의 현재값: "+i);
        }
        System.out.println("---------------------\n");
        
        
        /*4. 제어변수의 초기화 혹은 반복 조건식에는 다른 변수를 사용할 수 있다.
         */
        int start = 41;
        int end = 45;
        System.out.println("4. 다른 변수 사용하기");
        
        for(int i = start; i<=end; i++) {
            System.out.println("i의 현재값: "+i);
        }
        System.out.println("---------------------\n");

        
        /*5. 만약 반복 조건식이 처음부터 false가 나오면?
         */
        System.out.println("5. 처음부터 false가 나오면?");
        for(int i=0; i<10; i++) {
            System.out.println("i의 현재값: "+i);
        }
        System.out.println("---------------------\n");

        
        

    }

}

 

중첩 for문

더보기
package day0910;
/*중첩 for문
 * 중첩 for문은
 * 바깥쪽 for문이 한번 실행되는 동안
 * 안쪽 for문은 전부 반복이 되는 형태이다.
 */

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

        for (int i = 1; i <= 3; i++) {
            
            for(int j=101; j<=104; j++) {
                System.out.printf("i의 현재값: [%d] j의 현재값: [%d]\n", i, j);
            }

            System.out.println("---------------------\n");

        }
    }

}

 

문제

/*For문에 대한 기본 예제들
 * 제한시간 30분
 * 
 * 1. 1부터 5까지 출력해라
 * 2. 10~7 츨력해라
 * 3. 7~11까지 짝수를 출력해라
 * 4. 사용자로부터 숫자를 입력받아서 1부터 그 수까지 출력해라
 * 5. 사용자로부터 숫자를 2개 입력받아서
 *  더 작은 수부터 더 큰수까지 출력해라
 * 6. 사용자로부터 숫자를 1개 입력받아서
 *  1부터 그 수까지의 합을 구하여 출력해라
 * 7. 사용자로부터 숫자를 1개 입력받아서
 *  1부터 그 수까지의 곱을 구하여 출력해라  
 */

더보기
package day0910;

import java.util.Scanner;

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

        // 내가 한거
        Scanner sc = new Scanner(System.in);

        // 1.
        System.out.println("1번");
        for (int i = 1; i <= 5; i++) {
            System.out.println("i값: " + i);
        }
        System.out.println("---------------------\n\n");

        // 2.
        System.out.println("2번");
        for (int i = 10; i >= 7; i--) {
            System.out.println("i값: " + i);
        }
        System.out.println("---------------------\n\n");

        // 3.
        System.out.println("3번");
        for (int i = 7; i <= 11; i++) {
            if (i % 2 == 0) {
                System.out.println("i값: " + i);
            }
        }
        System.out.println("---------------------\n\n");

        // 4.
        System.out.println("4번");
        System.out.println("숫자를 입력하세요: ");
        System.out.println("> ");
        int num = sc.nextInt();

        for (int i = 1; i <= num; i++) {
            System.out.println("i값: " + i);
        }
        System.out.println("---------------------\n\n");

        // 5.
        System.out.println("5번");

        System.out.println("첫번째 작은 숫자를 입력하세요: ");
        System.out.println("> ");
        int num1 = sc.nextInt();
        System.out.println("첫번째보다 큰 숫자를 입력하세요: ");
        System.out.println("> ");
        int num2 = sc.nextInt();

        int start;
        int end;

        if (num1 < num2) {
            start = num1;
            end = num2;
        } else {
            start = num2;
            end = num1;
        }
        for (int i = start; i <= end; i++) {
            System.out.println("입력한 범위의 값: " + i);
        }
        System.out.println("---------------------\n\n");

        // 6. 사용자로부터 숫자를 1개 입력받아서 1부터 그 수까지의 합을 구하여 출력해라
        System.out.println("6번");

        // 합을 저장할 변수
        int sum = 0;

        System.out.println("숫자를 입력하세요: ");
        System.out.println("> ");
        num = sc.nextInt();

        for (int i = 1; i <= num; i++) {
            sum += i;
        }
        System.out.printf("1부터 %d까지의 합: %d\n", num, sum);

        System.out.println("---------------------\n\n");

        // 7. 사용자로부터 숫자를 1개 입력받아서 1부터 그 수까지의 곱을 구하여 출력해라
        System.out.println("7번");

        sum = 1;

        System.out.println("숫자를 입력하세요: ");
        System.out.println("> ");
        num = sc.nextInt();

        for (int i = 1; i <= num; i++) {
            sum *= i;
        }
        System.out.printf("1부터 %d까지의 곱: %d\n", num, sum);

        System.out.println("---------------------\n\n");

        sc.close();

    }
}

 

문제 1.

더보기
package day0910;
/*퀴즈
 * 구구단을 출력하는 프로그램을 작성하시오.
 * 단, 몇단인지는 i for문으로 출력하고
 * a x b = ab 는 j for문으로 출력하시오
 */
public class Ex04Gugudan {
    public static void main(String[] args) {      
        
//        //내가 한거
//        for(int i=1; i<=9; i++) {
//            System.out.printf("\n---- %d단 ----\n", i);
//            
//            for(int j=1; j<=9; j++) {
//                System.out.printf("%d x %d = %d\n", i, j, i*j);
//            }
//        }
        
        //쌤이 한거
        for(int i=2; i<=9; i++) {
            System.out.println("--------------------");
            System.out.println(i+"단");
            System.out.println("--------------------");

            for(int j=1; j<=9; j++) {
                System.out.printf("%d x %d = %d\n", i, j, i*j);
            }
            System.out.println();
            
            
        }
        
    }

}

 

문제 2.

 * 별찍기 (day 0910)
1. 번호 하나당 클래스 하나가 나온다.
2. 모든 별찍기는 사용자로 부터 입력을 받아서 입력 받은거에 맞는 줄 수가 출력 된다.
3. 아래 예제들은 모두 사용자가 5라고 입력했을 때 출력되는 모양이다.
4. 7~10번은 비록 9줄이 나와있지만 마찬가지로 사용자가 5라고 입력했을 때 출력되는 모양이다.
1.      2.     3.     4.
*       *****     *   *****
**      ****     **    ****
***     ***     ***     ***
****    **     ****      **
*****   *     *****       *

5.      6.
    *       *********
   ***       *******
  *****       *****
 *******       ***
*********       *

7.          8.      9.      10.
*           *       *       *********
**         **      ***      **** ****
***       ***     *****     ***   ***
****     ****    *******    **     **
*****   *****   *********   *       *
****     ****    *******    **     **
***       ***     *****     ***   ***
**         **      ***      **** ****
*           *       *       *********