Backend/JAVA

[JAVA] 특강 13일차 : 코딩 훈련! 문제 풀이 (연산자&제어문&반복문)

JOKUN 2022. 7. 7. 13:47

 

 

 

practice1

VariablePractice1

📑문제

🔍풀이

package com.kh.practice1.func;

import java.util.Scanner;

public class VariablePractice1 {
    public void run(){
        Scanner sc = new Scanner(System.in);
        System.out.print("이름을 입력하세요 : ");
        String name = sc.nextLine();
        System.out.print("성별을 입력하세요(남/여) : ");
        String gender = sc.nextLine();
        System.out.print("나이를 입력하세요 : ");
        int age = sc.nextInt();
        System.out.print("키를 입력하세요 : ");
        float height = sc.nextFloat();
        System.out.println();

        System.out.printf("키 %.1fcm인 %d살 %s자 %s님 반갑습니다^^",+height,age,gender,name);
    }
}
package com.kh.practice1.run;

import com.kh.practice1.func.VariablePractice1;


public class Run {
    public static void main(String[] args) {
      new VariablePractice1().run();

    }
}

 

 

 

VariablePractice2

📑문제

🔍풀이

package com.kh.practice1.func;

import java.util.Scanner;

public class VariablePractice2 {
    public void run(){
        Scanner sc = new Scanner(System.in);
        System.out.print("첫 번째 정수 : ");
        int num1 = sc.nextInt();
        System.out.print("두 번째 정수 : ");
        int num2 = sc.nextInt();

        int add = num1 + num2;
        int sub = num1 - num2;
        int mul = num1 * num2;
        int div = num1 / num2;

        System.out.println("더하기 결과 : " + add);
        System.out.println("빼기 결과 : " + sub);
        System.out.println("곱하기 결과 : " + mul);
        System.out.println("나누기 몫 결과 : " + div);
    }
}
package com.kh.practice1.run;

import com.kh.practice1.func.VariablePractice2;


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

        new VariablePractice2().run();


    }
}

 

 

 

VariablePractice3

📑문제

🔍풀이

package com.kh.practice1.func;

import java.util.Scanner;

public class VariablePractice3 {
    public void run(){
        Scanner sc = new Scanner(System.in);
        System.out.print("가로 : ");
        float num1 = sc.nextFloat();
        System.out.print("세로 : ");
        float num2 = sc.nextFloat();

        System.out.println("면적 : " + num1 * num2);
        System.out.println("둘레 : " + (num1+num2) * 2);
    }
}
package com.kh.practice1.run;

import com.kh.practice1.func.VariablePractice3;

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

        new VariablePractice3().run();


    }
}

 

 

 

VariablePractice4

📑문제

🔍풀이

package com.kh.practice1.func;

import java.util.Scanner;

public class VariablePractice4 {
    public void run(){
        Scanner sc = new Scanner(System.in);
        System.out.print("문자열을 입력하세요 : ");
        String text = sc.nextLine();

        System.out.println("첫 번째 문자 : " + text.charAt(0));
        System.out.println("두 번째 문자 : " + text.charAt(1));
        System.out.println("세 번째 문자 : " + text.charAt(2));

    }
}
package com.kh.practice1.run;

import com.kh.practice1.func.VariablePractice4;

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

        new VariablePractice4().run();

    }
}

 

 

 

practice2

[Run 실행 클래스 통합] 주석 풀어서 사용

package com.kh.practice2.run;

import com.kh.practice2.func.CastingPractice1;
import com.kh.practice2.func.CastingPractice2;

public class Run {
    public static void main(String[] args) {
//    new CastingPractice1().run();
        new CastingPractice2().run();

    }
}

CastingPractice1

📑문제

🔍풀이

package com.kh.practice2.func;

import java.util.Scanner;

public class CastingPractice1 {
    public void run() {
        Scanner sc = new Scanner(System.in);

        for(int i = 0; i <2; i++){
        System.out.print("문자 : ");
        String text1 = sc.nextLine();
        char ch = text1.charAt(0);
        System.out.print(text1 + "unicode : " + (int)ch);
        System.out.println();
        }
    }
}

 

 

 

CastingPractice2

📑문제

🔍풀이

package com.kh.practice2.func;

import java.util.Scanner;

public class CastingPractice2 {
    public void run() {
        Scanner sc = new Scanner(System.in);
        System.out.print("국어 : ");
        float kor = sc.nextFloat();
        System.out.print("영어 : ");
        float eng = sc.nextFloat();
        System.out.print("수학 : ");
        float math = sc.nextFloat();

        float total = kor+eng+math;
        float avg = total / 3;
        System.out.println("총점 : " + (int)total);
        System.out.println("평균 : " + (int)avg);


    }
}

 

 

 

practice3

run & controller (10문제)

클래스 하나에 메소드 여러개 작성, run클래스에서 메소드 호출하여 실행

📑문제

 

 

🔍풀이

package com.kh.practice3;

public class Run {
    public static void main(String[] args) {
        controller con = new controller();
//        con.practice1();
//        con.practice2();
//        con.practice3();
//        con.practice4();
//        con.practice5(); 
//        con.practice6();
//        con.practice7();
//        con.practice8();
//        con.practice9();
        con.practice10();

    }
}
package com.kh.practice3;

import java.util.Scanner;

public class controller {
    private  Scanner sc;
    public controller() {
        sc = new Scanner(System.in);
    }

    public void practice1(){
        System.out.print("정수 : ");
        int num = sc.nextInt();

        if (num >= 0 ){
            System.out.println("양수다");
        }else {
            System.out.println("양수가 아니다.");
        }
    }

    public void practice2(){
        System.out.print("정수 : ");
        int num = sc.nextInt();

        if (num > 0 ){
            System.out.println("양수다");
        }else {
            if(num == 0){
                System.out.println("0이다");
            } else {
            System.out.println("음수다");
            }
        }
    }

    public void practice3(){
        System.out.print("정수 : ");
        int num = sc.nextInt();

        if (num % 2 == 0 ){
            System.out.println("짝수다");
        }else {
            System.out.println("홀수다");
            }
        }

    public void practice4(){
        System.out.print("인원 수 : ");
        int num1 = sc.nextInt();
        System.out.print("사탕 개수 : ");
        int num2 = sc.nextInt();

        System.out.println("1인당 사탕 개수 : " + num2 / num1);
        System.out.println("남는 사탕 개수 : " + num2 % num1);
    }

    public void practice5(){
        System.out.print("이름 : ");
        String name = sc.nextLine();
        System.out.print("학년(숫자만) : ");
        int grage = sc.nextInt();
        System.out.print("반(숫자만) : ");
        int cls = sc.nextInt();
        System.out.print("번호(숫자만) : ");
        int number = sc.nextInt();
        sc.nextLine(); //버퍼 삭제
        System.out.print("성별(M/F) : ");
        String gender = sc.nextLine();
        System.out.print("성적(소수점 아래 둘째자리까지) : ");
        float jumsu = sc.nextFloat();

        if(gender.charAt(0) =='F' || gender.charAt(0) =='f'){
            gender = "여";
        }else {
            gender = "남";
        }

        String result = String.format("%d학년 %d반 %d번 %s %s학생의 성적은 %.2f이다.",
                grage, cls, number, name, gender, jumsu);
        System.out.println(result);
    }

    public void practice6(){
        System.out.print("나이 : ");
        int age = sc.nextInt();

        if(age <= 13){
            System.out.println("어린이");
        } else if (13 < age && age <= 19) {
            System.out.println("청소년");
        }else if (age > 19){
            System.out.println("성인");
        }
    }

    public void practice7(){
        System.out.print("국어 : ");
        float kor = sc.nextFloat();
        System.out.print("영어 : ");
        float eng = sc.nextFloat();
        System.out.print("수학 : ");
        float math = sc.nextFloat();

        float total = kor+eng+math;
        float avg = total / 3;

        System.out.println("합계 : " + (int)total);
        System.out.println("평균 : " + avg);

        if((kor >= 40 && eng >+ 40 && math >= 40) && avg >= 60){
            System.out.println("합격");
        }else {
            System.out.println("불합격");
        }
    }

    public void practice8(){
        System.out.print("주민번호를 입력하세요(-포함) : ");
        String jumin = sc.nextLine();

        if(jumin.indexOf("-") == -1){
            System.out.println("(-포함)이라고 했습니다!");
            return;
        }

        String[] splitJumin = jumin.split("-");
        if (splitJumin.length == 2){
            char genCh = splitJumin[1].charAt(0);
            if(genCh == '1' || genCh == '3'){
                System.out.println("남자");
            }else {
                System.out.println("여자");
            }
        }else {
            System.out.println("123456-1234567 형식으로 입력 바랍니다.");
        }
    }

    public void practice9(){
        System.out.print("정수1 : ");
        int num1 = sc.nextInt();
        System.out.print("정수2 : ");
        int num2 = sc.nextInt();
        System.out.print("입력 : ");
        int num3 = sc.nextInt();

        if(num1 > num2){
            System.out.println("num1은 num2보다 작아야합니다.");
            return;
        }

        if (num2 < num3 || num3 <= num1 ){
            System.out.println("true");
        }else {
            System.out.println("flase");
        }
    }

    public void practice10(){
        System.out.print("입력1 : ");
        int num1 = sc.nextInt();
        System.out.print("입력2 : ");
        int num2 = sc.nextInt();
        System.out.print("입력3 : ");
        int num3 = sc.nextInt();

        System.out.println(num1 == num2 && num2 == num3);
    }
}

 

 

 

practice4

IdPassword & Administrator rights (2문제)

하나의 클래스에 메소드로 정의하여 메소드 호출하여 실행

📑문제

🔍풀이

package com.kh.practice4;

import java.util.HashMap;
import java.util.Scanner;

public class IdPassword {
    public static void main(String[] args) {
//        method1();
        method2();

    }

    /**
     * 로그인 성공시 "로그인 성공"
     * 아이디 틀렸을시 "아이디가 틀렸습니다."
     * 비밀번호 틀렸을시 "비밀번호가 틀렸습니다."
     *
     * id : myId
     * pw : myPassword12
     */
    private static void method1(){
        Scanner sc = new Scanner(System.in);
        System.out.print("아이디 입력 : ");
        String id = sc.nextLine();
        System.out.print("패스워드 입력 : ");
        String pw = sc.nextLine();

        String chkId = "myId";
        String chkPw = "myPassword12";

        if(id.equals(chkId) && pw.equals(chkPw)){
            System.out.println("로그인 성공");
        }else {
            if(!id.equals(chkId)){
                System.out.println("아이디가 틀렸습니다.");
            }
            if(!pw.equals(chkPw)){
                System.out.println("비밀번호가 틀렸습니다.");
            }
        }
    }


    /**
     * HashMap<String, String> key = value
     * 관리자 = (회원관리, 게시글 관리, 게시글 작성, 게시글 조회, 댓글)
     * 회원 = (게시글 작성, 게시글 조회, 댓글)
     * 비회원 = (게시글 조회)
     */
    private static void method2(){
        HashMap<String, String> dataMap = new HashMap<>();
        dataMap.put("관리자", "회원관리, 게시글 관리, 게시글 작성, 게시글 조회, 댓글");
        dataMap.put("회원", "게시글 작성, 게시글 조회, 댓글");
        dataMap.put("비회원", "게시글 조회");

        Scanner sc = new Scanner(System.in);
        System.out.print("권한을 확인하고자 하는 회원 등급 : ");
        String memberGrade = sc.nextLine();
        System.out.println(dataMap.get(memberGrade));
    }
}

 

 

 

practice5

LoopControl (5문제)

하나의 클래스에 메소드로 정의하여 메소드 호출하여 실행

📑문제

🔍풀이

package com.kh.practice5;

import java.util.*;
import java.util.stream.Stream;

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

//        method1();
//        method2();
//        method3();
//        method4();
        method5();

    }

    private static void method1(){
        Scanner sc = new Scanner(System.in);
        System.out.print("정수 : ");
        int num = sc.nextInt();

        for (int i = 1; i <= 9; i++){
            if(i % 3 == 0){
                continue;
            }
            System.out.println(num + " * " + i + " = " + num*i);
        }
    }


    /**
     * 정답입니다.
     * 주사위의 합 : 5
     * 계속 하시겠습니까?(y/n) : y
     * 틀렸습니다.
     * 종료합니다.
     */
    private static void method2() {
        Scanner sc = new Scanner(System.in);

        while (true){
        System.out.print("주사위 두 개의 합을 맞춰보세요(1~12입력) : ");
        int num = sc.nextInt();
        sc.nextLine();

        Random ran = new Random();
        int ran1 = ran.nextInt(6) + 1;
        int ran2 = ran.nextInt(6) + 1;

        int ranSum = ran1 + ran2;

        if(num == ranSum){
            System.out.println("정답입니다.");
            System.out.println("주사위의 합 : " + ranSum);
            System.out.print("계속 하시겠습니까?(y/n) : ");
            String yn = sc.nextLine();
            yn = yn.toLowerCase();
            if(yn.equals("n")) {
                break;
            }
        }else{
            System.out.println("틀렸습니다.");
        }
        }
    }
    private static void method3() {
        Scanner sc = new Scanner(System.in);
        System.out.print("비밀번호 입력(1000~9999) : ");
        String numStr = sc.nextLine();

        if(!numStr.matches("^[0-9]*$")){
            System.out.println("숫자만 입력할 수 있습니다.");
            return;
        }

        if (numStr.length() != 4) {
            System.out.println("자리 수 안맞음");
            return;
        }

        if (numStr.charAt(0) == '0') {
            System.out.println("첫번째 자리 수는 0이 올 수 없습니다.");
            return;
        }


        List<Integer> numList = new ArrayList<>();
        int number = Integer.parseInt(numStr);
        while (number > 0){ //반복문 돌려서 숫자하나씩 쪼개기
            numList.add(number % 10);
            number = number / 10;
        }

        long count = numList.stream().distinct().count(); //distinct 중복체크!
        if(numList.size() == count){ // 중복 없음
            System.out.println("성공");
       }else{
            System.out.println("실패(중복 값 있음)");
        }
    }
    private static void method4() {
        Scanner sc = new Scanner(System.in);
        System.out.print("1 이상의 숫자를 입력하세요 : ");
        int num = sc.nextInt();

        if(num < 1){
            System.out.println("1 이상의 숫자를 입력하세요");
            return;
        }

        for (int i = 1; i <= num; i++){
            System.out.print(i + " ");
        }
    }
    private static void method5(){
        Scanner sc = new Scanner(System.in);
        System.out.print("1 이상의 숫자를 입력하세요 : ");
        int num = sc.nextInt();

        while (true){
            if(num < 1){
                if(num == -1){
                    System.out.println("종료되었습니다.");
                    break;
                }
            System.out.println("1 이상의 숫자를 입력하세요");
            }else {
                for (int i = 1; i <= num; i++){
                System.out.print(i + " ");
                }
                System.out.println();
            }
        }
    }
}