제어문
: 코드의 흐름을 제어하는 문장(문법)
코드의 일정 부분을 선택하여 실행하거나
코드의 일정 부분을 반복하여 실행하는 제어문
제어문의 종류
조건문
: if ~ else문
조건식의 결과가 참과 거짓에 따라 실행 내용을 선택하여 실행하는 제어문
조건문 설명 : https://developernew.tistory.com/13
선택문
: swich ~ case문
값에 따라 실행 내용을 선택하여 실행
선택문 설명 : https://developernew.tistory.com/14
반복문
: while, for, do ~ while
코드의 일정 부분을 반복하여 실행하는 제어문
조건식이 [참]일 동안 반복하여 실행한다 ; [거짓]이 될 때 종료함
반복문 설명: https://developernew.tistory.com/18
조건문
조건문의 형태에 따른 분류
단순 if문
: 조건식의 결과가 참일 때만 추가적인 실행
조건식이 참이라면 종속문이 실행된다
if(조건식) {
종속문장 : if문의 내용
}
if ~ else문
: 조건식의 결과가 참고 ㅏ거짓에 따라 실행내용을 선택
내가 생각하지 못한 경우의 수를 else로 실행
if(조건식) {
종속문장;
} else {
종속문장;
}
if ~ else if ~else문
: 조건식이 좀 더 세분화 되어야 하는 경우
조건식이 여러 개 필요한 상황에 사용
if(조건식) {
종속문장;
} else if (조건식) {
종속문장;
} else {
종속문장;
}
Math.random()
0부터 1미만의 임의의 실수를 구하여 반환하는 메소드
0.0000000000000000000000000 ~ 0.99999999999999999999999999999
범위 안의 임의의 수 구하기
(int)(Math.random() * 범위 안의 수의 개수) + 시작수
e.g) 20~23
double a = Math.random(); // 0.0000 ~ 0.9999
double b = a * 4; // 0.0000 ~ 3.9999
int c = (int)b; // 0 ~ 3
int d = c + 20; // 20 ~ 23
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d);
=>
int ran = (int)(Math.random() * 4) + 20;
System.out.println(ran);
Exercise 1
정수를 입력받고 if문을 사용하여 짝수와 홀수를 확인하고 다음과 같이 출력하시오
짝수일때 : (입력받은 정수)는 짝수입니다
홀수일때 : (입력받은 정수)는 홀수입니다
import java.util.Scanner;
public class Test01 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("정수를 입력하세요");
int su = sc.nextInt();
if (su == 0) {
System.out.println("0은 사용할 수 없습니다");
} else if (su %2 == 0) {
System.out.println(su + "은(는) 짝수입니다");
} else {
System.out.println(su + "은(는) 홀수입니다");
}
}
}
Exercise 2
사용자에게 출생년도 4자리를 입력받아 나이를 계산해서 화면에 출력
2004년생 -> 20살
1996년생 -> 28살
n년생 -> ?살
나이가 20살 이상이면 [성인입니다!] 출력
나이가 20살 미만이면 [미성년자입니다!] 출력
import java.util.Scanner;
public class Test02 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("출생년도 4자리를 입력해주세요");
int birth = sc.nextInt();
System.out.println(birth + "년생");
// System.currentTimeMillis();
// 1970년 1월 1일 0시 0분 0초부터 지금까지의 시간을 밀리언 초 단위로 반환하는 메소드
// -1000ms == 1s
long a = System.currentTimeMillis(); // ms
long b = a / 1000; // s
long c = b / 60; // m
long d = c / 60; // h
long e = d / 24; // d
long f = e / 365; // y
long g = f + 1970; // 올해
// System.out.println(g);
int sysy = (int)(System.currentTimeMillis() / 1000 / 60 / 60 / 24 / 365) + 1970;
int age = sysy - birth +1;
System.out.println(age + "살");
if(birth >= 20) {
System.out.println("성인입니다");
} else {
System.out.println("미성년자입니다");}
}
}
Exercise 3
중국집 주문 프로그램
사용자에게 짜장면, 짬뽕 주문 수량을 입력받아 결제 금액을 계산하여 출력
짜장면 5000원
짬뽕 6000원
5그릇 이상 주문하면 3천원 할인
10그릇 이상 주문하면 10%할인
import java.util.Scanner;
public class Test03 { public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("주문수량을 입력하세요");
System.out.println("짜장면 5000원, 짬뽕 6000원");
System.out.println("짜장면");
int order1 = sc.nextInt();
System.out.println("짬뽕");
int order2 = sc.nextInt();
int price1 = 5000;
int price2 = 6000;
int rate1 = 10;
int rate2 = 3000;
int discount1 = 5;
int discount2 = 10;
int tot = order1 + order2;
int sum = order1*price1 + order2*price2;
// 바뀔 수 있는 모든 항목을 변수로 처리해줌
System.out.println("===============================");
System.out.println("짜장면 : " + order1 + "개, " + price1 + "원");
System.out.println("짬뽕 : " + order2 + "개, " + price2 + "원");
System.out.println("합계 : " + sum + "원");
if (tot >= discount2) {
System.out.print(discount2 + "그릇 이상 주문 시 10% 할인 금액 : " + (int)(sum*(100-rate1)/100) + "원");
} else if (tot >= discount1) {
System.out.print(discount1 + "그릇 이상 주문 시 3천원 할인 금액 : " + (sum - rate2) + "원" );
}
}
}
출력화면



Exercise 4
주사위를 2개 던지는 코드를 구현하고
두 개의 주사위 합계에 따라 아래와 같이 코드를 구현
1. 합계가 짝수일 경우 : [짝!] 출력
2. 합계가 홀수일 경우 : [홀!] 출력
3. 두 주사위가 같은 값일 경우 : [더블!] 출력
import java.util.Scanner;
public class Test04 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int ran1 = (int)(Math.random() * 6 + 1);
int ran2 = (int)(Math.random() * 6 + 1);
System.out.println("주사위 숫자");
System.out.println(ran1);
System.out.println(ran2);
if (ran1 == ran2) {
System.out.println("더블!");
} else if ((ran1+ran2) %2 == 0 ) {
System.out.println("짝!");
} else {
System.out.println("홀!");
}
}
}
출력화면
Exercise 5
점수를 3개 입력 받아
평균이 60점 이상이고 각 점수가 40점 이상이면 합격, 아니면 불합격
불합격한 경우 그 사유를 알려줄 것
import java.util.Scanner;
public class Test05 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("국어 영어 수학 점수를 입력하세요");
int sub1 = sc.nextInt();
int sub2 = sc.nextInt();
int sub3 = sc.nextInt();
double avg = (sub1 + sub2 + sub3) / 3;
System.out.println("=====================================");
System.out.println("평균: " + avg);
if (avg >= 60 && sub1 >= 40 && sub2 >= 40 && sub3 >= 40) {
System.out.println("합격");
} else {
System.out.println("불합격");
System.out.print("불합격 사유 : ");
if (avg < 60) {
System.out.println("평균");
}
if (sub1 < 40) {
System.out.println("국어");
}
if (sub2 < 40) {
System.out.println("영어");
}
if (sub3 < 40) {
System.out.println("수학");
}
System.out.println("미달");
}
}
출력화면
Exercise 6
영문자를 입력 받아 대, 소문자를 구분한 뒤
소문자는 대문자로, 대문자는 소문자로 서로 변환하여 출력
특수문자 및 숫자를 입력할 시 잘못된 입력이라는 문구 표시
import java.util.Scanner;
public class Test06 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("영문자를 입력하세요");
char ch = sc.next().charAt(0);
/*
아스키 코드
구분 십진법
A ~ Z (대문자) 65 ~ 90
a ~ z (소문자) 97 ~ 122
0 ~ 9 (숫자) 48 ~ 57
*/
if (ch >= 65 && ch <=90) {
System.out.println(ch + " 의 소문자 : " + (char)(ch+32));
} else if (ch >= 97 && ch <= 122) {
System.out.println(ch + " 의 대문자 : " + (char)(ch-32));
} else {
System.out.println("잘못된 입력입니다");
}
/* 동일한 방법
if (ch >= 'A' && ch <= 'Z') {
System.out.println(ch + " 의 소문자 : " + (char)(ch+32));
} else if (ch >= 'a' && ch <= 'z') {
System.out.println(ch + " 의 대문자 : " + (char)(ch-32));
} else {
System.out.println("잘못된 입력입니다");
}
*/
}
}
출력화면
Exercise 7
화면에 무작위로 구구단 1문제를 출제 (2 ~ 15단)
2 X 1 = 부터 15 X 9 = 까지
사용자가 정답을 입력할 수 있도록 프로그래밍 코드를 구현 (Scanner)
1. 맞춘 경우 [정답! 10점 획득!]
2. 틀린 경우 [오답! 5점 감점!]
어려운 문제(11단 이상)를 맞추면 10점을 추가로 획득하도록 코드 구현
import java.util.Scanner;
public class Test07 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double a = Math.random();
int ran1 = (int)((Math.random() * 14) +2);
int ran2 = (int)((Math.random() * 9) + 1);
System.out.println(ran1 + " X " + ran2 + "= ?");
int ans = sc.nextInt();
if (ans != ran1 * ran2) {
System.out.println("오답! 5점 감점");
} else {
System.out.println("정답! 10점 획득");
if (ran1 >= 11) {
System.out.println("축하합니다! 어려운 문제를 맞춰 10점 추가 획득!");
}
}
}
}
출력화면


Exercise 7
국어, 영어, 수학 성적을 입력 받고 평균 점수를 구하고,
평균에 대한 학점을 출력하세요
90이상 : A
80이상 90미만 : B
70이상 80미만 : C
60이상 70미만 : D
60미만 : F
또한, 세 과목의 평균이 60점 이상이면 ‘합격’,
미만이면 ‘불합격’을 출력하세요.
import java.util.Scanner;
public class Test07 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// JAVA의 모든 스트림은 사용 후 정리를 해 주어야 함
// -> close 사용 (가장 하단에)
System.out.println("국어 점수 입력 : ");
int kor = sc.nextInt();
System.out.println("영어 점수 입력 : ");
int eng = sc.nextInt();
System.out.println("수학 점수 입력 : ");
int mth = sc.nextInt();
int avg = (kor + eng + mth)/3;
System.out.println("===================================");
System.out.println("평균 : " + avg);
System.out.print("학점 : ");
if (avg < 60) {
System.out.println("F");
System.out.println("불합격");
} else if (avg < 70) {
System.out.println("D");
System.out.println("합격!");
} else if (avg < 80) {
System.out.println("C");
System.out.println("합격!");
} else if (avg < 90) {
System.out.println("B");
System.out.println("합격!");
} else {
System.out.println("A");
System.out.println("합격!");
}
/* 다른 방법
if(avg >= 90 ) {
System.out.println("학점 : A\n합격!");
} else if (avg >= 80) {
System.out.println("학점 : B\n합격!");
} else if (avg >= 70) {
System.out.println("학점 : C\n합격!");
} else if (avg >= 60) {
System.out.println("학점 : D\n합격!");
} else if (avg >= 50) {
System.out.println("학점 : F\n불합격!");
}
*/
sc.close();
// 더이상 이 스캐너를 사용하지 않겟다
}
}
출력화면
와 이제 벌써부터 머리 터지게 문제 풀기 시작했습니다
하루에도 몇 개씩 풀고 있습니다
혹시나 틀린 게 있다면 말해주세요 고치게
제가 더 나은 사람이 될 수 있게
'Backend > JAVA' 카테고리의 다른 글
JAVA 코딩 제어문 - 반복문 : while, for, do ~ while문 (0) | 2023.02.06 |
---|---|
JAVA 코딩 제어문 - 선택문 : switch ~ case문 (0) | 2023.02.03 |
JAVA 코딩 System.in 표준 입력 스트림, Scanner 스캐너 (0) | 2023.02.01 |
JAVA Stream, 제어문자, 서식문자 (0) | 2023.01.31 |
JAVA 논리 자료형 / 문자 자료형 / 문자열 자료형(참조형) (0) | 2023.01.31 |