Programming/국비학원

220421 - 연산자, 조건문, 반복문

지고르 2022. 4. 22. 11:53
  • 과제 풀이

import java.util.Scanner;

public class test2 {

 

   public static void main(String[] args) {

      Scanner sc = new Scanner (System.in);

      System.out.print("금액 입력>> ");

      int money = sc.nextInt(); 

 

      int tenThousand = money/10000;

      money %= 10000;    //money = money%10000;    //나머지 9500
      int fiveThousand = money/5000;
 
      money %= 5000;
      int thousand = money/1000;

      money %= 1000;
      int fiveHundred = money/500;
      
      money %= 500;
      int hundred = money/100;
      
      money %= 100;
      int ten = money/10;

 

      System.out.println("만원 => "+ tenThousand + " 장");
      System.out.println("오천원 => "+ fiveThousand + " 장");
      System.out.println("천원 => "+ thousand + " 장");
      System.out.println("오백원 => "+ fiveHundred + " 개");
      System.out.println("백원 => "+ hundred + " 개");
      System.out.println("십원 => "+ ten + " 개");
   }}

 

 

연산자
  • 산술연산자 : + - * / %
  • 비교연산자 : < <= > >= == != 
  • 논리연산자 : &&(AND) ||(OR) !(NOT : inverter, 답을 반대로 만듦)

 

 

 

조건문 if - 대소 비교 편리
  • 단순 if

if (조건) {
...
...}

 

 

 

  • 참/거짓

if (조건) 명령문1;    => 참일 때
명령문2;     => 거짓일 때

 

 

 

  • ★기본 if

if (조건) {
명령문1;
else {
명령문2;
}

 

 

 

  • else if

if (조건) {
...
} else if (조건2){
....
} else if (조건3){
...
} else {}

 

 

 

  • 중첩 if 1

if (조건) {
  if (조건){
    ...
  } else {
    ...
  }
}

 

 

 

  • 중첩 if 2

if (조건) {
 if (조건){
...
  }
} else {
...
}

 

 

 

  • 단순 if 문제

콘솔로 수량을 입력받아 판매금액을 계산하는 프로그램을 완성하시오.
예시:
import java.util.Scanner;

public class IFStatementEx2 {

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

System.out.print("구입수량은? ");

int amount = sc.nextInt();
int price = 5000;
}}
조건1: 수량 10개 이상 구입시 20% 할인

 

 

 

  • 풀이1

import java.util.Scanner;

public class IFStatementEx2 {

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

System.out.print("구입수량은? ");

int amount = sc.nextInt();
int price = 5000;
if (amount>=10) {
price = (int) (price * 0.8);
}
int result = amount * price;
System.out.println(result+"원");
}}

 

 

 

  • 풀이2

import java.util.Scanner;

public class IFStatementEx2 {

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("구입수량은? ");
int amount = sc.nextInt();
int price = 5000;
if (amount>=10) {
price *= 0.8;    //복합연산자는 자동 형변환시켜줌 => 데이터타입 변환 오류 없음 
}
int result = amount * price;
System.out.println(result+"원");
}}

 

 

 

  • 위 if문제 + 조건2: 1000원 미만 품목은 할인 제외

import java.util.Scanner;

public class IFStatementEx2 {

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("구입수량은? ");
int amount = sc.nextInt();
int price = 100;
if (amount>=10 && price>=1000) {
price *= 0.8;
}
int result = amount * price;
System.out.println(result+"원");
}}

//

구입수량은? 100
10000원

 

 

 

  • &&

import java.util.Scanner;

public class IFStatementEx3 {

public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
System.out.print("당신의 나이는? ");
int age = sc.nextInt();

if (20 <= age && age <30) {
System.out.println("상품 가입이 가능합니다.");
} else { System.out.println("가입할수 없는 상품입니다.");
}
}
}

 

 

 

  • 논리연산자 !

public class IFStatementEx4 {

public static void main(String[] args) {
boolean play = false;
System.out.println(play);
play = !play;
System.out.println(play);
play = !play;
System.out.println(play);
}}
//
false
true
false

 

 

 

  • else if 문제

시험점수 80점 이상 => 합격
70~79점 => 대기자
69점 이하 => 불합격

public class IFStatementEx5 {

public static void main(String[] args) {
int score = 90;
if (score >= 80) {
System.out.println("합격");
} else if (70<=score) {    //앞에 조건1과 불일치하는 else if이므로 score<80 쓸 필요 없음
System.out.println("대기자");
} else {
System.out.println("불합격");
}
}
}

 

 

 

  • else if 문제

콘솔로 점수를 입력받아 등급을 계산하는 프로그램을 완성하시오.
90~100점 A등급
80~89점 B등급
70~79점 C등급
60~69점 D등급
59점 이하 F등급

 

=>

import java.util.Scanner;

public class IFStatementEx6 {

public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
System.out.print("점수를 입력해주세요>> ");
int score = sc.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등급");
}}}

※println은 메소드

 

 

 

  • 중첩 if 1

Scanner sc = new Scanner (System.in);
System.out.print("점수를 입력해주세요>> ");
int score = sc.nextInt();
if (score >= 0 && score<=100{
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 {
System.out.println("점수입력 오류");
}
}

 

 

 

  • 중첩 if 2

Scanner sc = new Scanner (System.in);
System.out.print("점수를 입력해주세요>> ");
int score = sc.nextInt();
if (score >= 0 && score<=100) {    // 0~100 만 다음 if로, 그 외는 else
if (score>=90) {    //90이상만 다음 if로, 90미만은 else if
if (score>=95) {    // 95이상은 다음 조건 실행, 95미만은 else
System.out.println("A+등급");
} else {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 {
System.out.println("점수입력 오류");}

 

 

  •  

 

 

 

 

 

 

조건문 switch -변수 선택 편리
  •  

switch (변수) {
  case 값:    //콜론
    명령문;
    ...
    ...
    break;    //★case마다 break 쓰기 (break 없으면 해당 변수 밑 케이스들까지 같이 출력)
  case 값:
    명령문;
    break;

    ...}

 

 

 

  •  

import java.util.Scanner;

public class SwitchEx1 {

public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
System.out.print("여행지를 선택 (1. 미주 2. 유럽 3. 동남아)?");
int choice = sc.nextInt();
switch (choice) {
case 1:   
System.out.println("1층 안내데스크로 가세요");
break;
case 2:
System.out.println("2층 안내데스크로 가세요");
break;
case 3:
System.out.println("별관 안내데스크로 가세요");
break;
}
}
}

 

=> if문 =>

 

if (choice == 1) {
 System.out.println("1층 안내데스크로 가세요");
} else if (choice == 2) {
 System.out.println("2층 안내데스크로 가세요");
} ~

 

 

 

  • default 추가

import java.util.Scanner;

public class SwitchEx1 {

public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
System.out.print("여행지를 선택 (1. 미주 2. 유럽 3. 동남아)?");
int choice = sc.nextInt();
switch (choice) {
case 1:
System.out.println("1층 안내데스크로 가세요");
break;
case 2:
System.out.println("2층 안내데스크로 가세요");
break;
case 3:
System.out.println("별관 안내데스크로 가세요");
break;
default:   => 변수 범위 벗어났을 때 실행 / 생략 가능
System.out.println("여행지 선택이 잘못되었습니다.");
}
}
}

 

 

 

  • 문제

콘솔로 점수를 입력받아 등급을 계산하는 프로그램 완성.
90 ~100 A
8~9
7~8
6~7
60 미만 F

 

import java.util.Scanner;

public class SwitchEx2 {

public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
System.out.print("점수>> ");
int score = sc.nextInt();
score/=10;    //int이므로 소수 절삭됨
 switch (score) {
  case 9 : 
  System.out.println("A등급");
  break;
  case 8 : 
  System.out.println("B등급");
  break;
  case 7 : 
  System.out.println("C등급");
  break;
  case 6 : 
  System.out.println("D등급");
  break;
  default : 
  System.out.println("F등급");
  break;
 }
}
}

 

 

 

  •  

public static void main(String[] args) {
char ch = 'a';
switch (ch) {
case 'a':
System.out.println("apple 선택 완료!!");
break;
case 'b':
System.out.println("banana 선택 완료!!");
break;
case 'c':
System.out.println("grape 선택 완료!!");
break;
default:
System.out.println("아직 준비 못했습니다.");
break;
}
}

//
apple 선택 완료!!

 

 

 

  • 같은 값 출력

public static void main(String[] args) {
char ch = 'A';
switch (ch) {
case 'A':
case 'a':
System.out.println("apple 선택 완료!!");
break;
case 'B':
case 'b':
System.out.println("banana 선택 완료!!");
break;
case 'C':
case 'c':
System.out.println("grape 선택 완료!!");
break;
default:
System.out.println("아직 준비 못했습니다.");
break;
}
}
}
//
apple 선택 완료!!

 

 

 

  • 100도 A등급에 포함되도록

public class SwitchEx2 {

public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
System.out.print("점수>> ");
int score = sc.nextInt();
score/=10;
 switch (score) {
  case 10: 
  case 9 : 
  System.out.println("A등급");
  break;
  case 8 : 
  System.out.println("B등급");
  break;
  case 7 : 
  System.out.println("C등급");
  break;
  case 6 : 
  System.out.println("D등급");
  break;
  default : 
  System.out.println("F등급");
  break;
 }
}

}
=> 100점 이상, 음수 입력 시 F등급으로 출력됨

=> if 없이 switch 만으로는 해당 문제 해결 불가

 

 

 

  • if, switch 혼용

import java.util.Scanner;

public class SwitchEx2 {

public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
System.out.print("점수>> ");
int score = sc.nextInt();
if (score>=0 && score<=100) {
score/=10;
 switch (score) {
  case 10: 
  case 9 : 
  System.out.println("A등급");
  break;
  case 8 : 
  System.out.println("B등급");
  break;
  case 7 : 
  System.out.println("C등급");
  break;
  case 6 : 
  System.out.println("D등급");
  break;
  default : 
  System.out.println("F등급");
  break;
 }
} else {
System.out.println("점수 입력 오류");
}

 

 

 

 

 

반복문 for (,while, do while)
  • for

for (초기화식;조건식;증감식) {
반복할 내용
}

 

 

 

  • for 반복문

public static void main(String[] args) {
        1       2 5    4 6
for (int i=1; i<=10; i++) {
System.out.println("모두 파이팅!");
}                 3 7
System.out.println("끝"); }

//
모두 파이팅!
모두 파이팅!
모두 파이팅!
모두 파이팅!
모두 파이팅!
모두 파이팅!
모두 파이팅!
모두 파이팅!
모두 파이팅!
모두 파이팅!

 

 

 

  • for 실행 x

public class ForEx1 {

public static void main(String[] args) {

for (int i=1; i>=10; i++) {
System.out.println(i + "모두 파이팅!");
}
System.out.println("끝");

}}
//끝

 

 

 

  • for (초기화값 변경)

public static void main(String[] args) {

for (int i=10; i>=1; i--) {
System.out.println(i + "모두 파이팅!");
}
System.out.println("끝");

}}
//
10모두 파이팅!
9모두 파이팅!
8모두 파이팅!
7모두 파이팅!
6모두 파이팅!
5모두 파이팅!
4모두 파이팅!
3모두 파이팅!
2모두 파이팅!
1모두 파이팅!

 

 

 

  •  

int price = 370;
for (int i=1; i<=10;i++) {
System.out.println(i + "개 가격= "+ price*i);
}}}
//
1개 가격= 370
2개 가격= 740
3개 가격= 1110
4개 가격= 1480
5개 가격= 1850
6개 가격= 2220
7개 가격= 2590
8개 가격= 2960
9개 가격= 3330
10개 가격= 3700

 

 

 

  • 2단 예시

public static void main(String[] args) {
int dan =2;
System.out.println("** " + dan + "단 **");
for (int i=1;i<=9;i++) {
System.out.println(dan + " X " + i + " = " + dan*i);
}}}
//
** 2단 **
2 X 1 = 2
2 X 2 = 4
2 X 3 = 6
2 X 4 = 8
2 X 5 = 10
2 X 6 = 12
2 X 7 = 14
2 X 8 = 16
2 X 9 = 18

 

 

 

  • 무작위값 예시 - 주사위

public static void main(String[] args) {
int num = (int)(Math.random()*6)+1;
System.out.println(num);
}}
// 1~6

 

 

 

  • 무작위값 예시 - 로또

public static void main(String[] args) {
System.out.println("로또 자동 번호 생성기");
for (int i=1;i<=6; i++) {
int num = (int)(Math.random()*45)+1;    //해당 코드 6번 반복
System.out.println(num);
}}}
//
39
39    => int로 강제형변환시키면서 뒤에 소수값 절삭했기 때문에 중복값 많이 나옴
22
18
37
43

 

 

 

  • 1~100 합

public static void main(String[] args) {
int sum = 0;
for (int i=1;i<=100;i++) {
sum+=i;
}
System.out.println("1부터 100가지의 합= "+sum);
}

}
//
1부터 100가지의 합= 5050

 

 

 

//중첩 if 약간 어질어질하다....ㅎ 계속 보고 쳐봐야지 익숙해질듯