210629 화
Chap01. 조건문
: 프로그램 수행 흐름을 바꾸는 역할을 하는 제어문 중 하나로 조건에 따라 다른 문장이 수행되도록 함
<If문>
1) If
package com.kh.chap01.condition;
import java.util.Scanner;
public class A_If {
/* 단독 if문
*
* if(조건식) {
* 실행할 코드;
* 실행할 코드2;
*
* }
* -> 조건식의 결과 값이 true면 중괄호 안의 코드 실행
* -> 조건식의 결과 값이 false면 코드 실행하지 않고 넘어감
* -> 실행할 코드가 1개 이상일 경우 반드시 {} 작성
*/
public void method1() {
// 연산자 실습의 삼항 연산자 문제를 if문으로 변환
// 양수, 0, 음수 판별
Scanner sc = new Scanner(System.in);
System.out.print("정수 : ");
int num = sc.nextInt();
if(num > 0) {
//들여쓰기 할 것
System.out.print("양수다");
}
if(num == 0) {
System.out.print("0이다");
}
if(num < 0) {
System.out.println("음수다");
System.out.println("음수일 경우 출력하고 싶은 문장");
}
}
public void method2() {
//짝홀판별
Scanner sc = new Scanner(System.in);
System.out.println("정수 : ");
int num = sc.nextInt();
if(num % 2 == 0) {
System.out.println("입력한 숫자는 짝수입니다");
}if(num % 2 == 1) {
System.out.println("입력한 숫자는 홀수입니다.");
}
}
public void method3() {
//성별 입력 받아 남학생/여학생 판별
Scanner sc = new Scanner(System.in);
System.out.print("성별(M/F) : ");
char gender = sc.next().charAt(0);
String student = "";
//지역변수는 반드시 초기화 되어야 한다. // 이부분 인강 다시 듣기
if(gender == 'M' || gender == 'm') {
student = "남학생";
}if(gender == 'F' || gender == 'f') {
student = "여학생";
}if(gender != 'M' && gender != 'm' && gender != 'F' && gender != 'f') {
System.out.println("잘못 입력하셨습니다.");
return;
}System.out.println(student + "이다");
}
public void method4() {
//입력된 이름이 본인이 맞는지 확인하는 메소드
Scanner sc = new Scanner(System.in);
System.out.print("이름을 입력하세요 : ");
String name = sc.next();
System.out.println(name);
/*
if(name == "우별림") {
System.out.println("본인 입니다");
}
if(name != "우별림") {
System.out.println("본인이 아닙니다");
}
기본 자료형은 ==, != 연산자를 통한 동등 비교가 가능하지만
String은 기본 자료형이 아닌 참조 자료형으로
String 클래스에서 제공하는 equals 메소드를 사용해서 값 비교를 해야함*/
if(name.equals("우별림")) {
System.out.println("본인입니다.");
}if(!name.equals("우별림")) {
System.out.println("본인이 아닙니다");
}
}
}
2) If~Else
package com.kh.chap01.condition;
import java.util.Scanner;
public class B_Else {
public void method1() {
//단독 if문으로 작성했던 코드 수정
//양수, 0, 음수 판별
Scanner sc = new Scanner(System.in);
System.out.print("정수 : ");
int num = sc.nextInt();
if(num > 0) {
//들여쓰기 할 것
System.out.print("양수다");
}else if(num == 0) {
System.out.print("0이다");
}else {
System.out.println("음수다");
System.out.println("음수일 경우 출력하고 싶은 문장");
}
}
public void method2() {
//짝홀판별
Scanner sc = new Scanner(System.in);
System.out.println("정수 : ");
int num = sc.nextInt();
if(num % 2 == 0) {
System.out.println("입력한 숫자는 짝수입니다");
}else {
System.out.println("입력한 숫자는 홀수입니다.");
}
}
public void method3() {
//성별 입력 받아 남학생/여학생 판별
Scanner sc = new Scanner(System.in);
System.out.print("성별(M/F) : ");
char gender = sc.next().charAt(0);
String student = "";
//지역변수는 반드시 초기화 되어야 한다. // 이부분 인강 다시 듣기
if(gender == 'M' || gender == 'm') {
student = "남학생";
}else if(gender == 'F' || gender == 'f') {
student = "여학생";
}else {
System.out.println("잘못 입력하셨습니다.");
return;
}
System.out.println(student + "이다");
}
public void method4() {
Scanner sc = new Scanner(System.in);
System.out.print("나이 : ");
int age = sc.nextInt();
String result = "";
if(age <= 13){
result = "어린이";
}else if(age <= 19) {
result = "청소년";
}else {
result = "성인";
}System.out.println(result);
}
public void method5() {
//사용자에게 점수를 입력 받아서
//점수별로 등급을 나눠 점수와 등급을 출력하는 메소드
//90점 이상 -> A
//90점 미만 80점 이상 -> B
//80점 미만 70점 이상 -> C
//70점 미만 60점 이상 -> D
//60점 미만 -> F
Scanner sc = new Scanner(System.in);
System.out.print("점수 : ");
int score = sc.nextInt();
String grade = "";
if(score > 0 && score <= 100) {
if(score >= 90) {
grade = "A";
}else if(score >= 80) {
grade = "B";
}else if(score >= 70) {
grade = "C";
}else if(score >= 60) {
grade = "D";
}else{
grade = "F";
}
else {
System.out.println("잘못 된 범위의 점수를 입력하였습니다.");
return;
}
System.out.println("당신의 점수는 " + score + "점이고, 등급은 " + grade + "입니다");
}
public void method6() {
//위의 메소드에서 각 등급별 중간 점수 이상(ex. 95, 85, 75, 65)의 경우
// 등급에 "+"라는 문자를 추가하여 출력
Scanner sc = new Scanner(System.in);
System.out.print("점수 : ");
int score = sc.nextInt();
String grade = "";
if(score > 0 && score <= 100) {
if(score >= 90) {
grade = "A";
if(score >=95) {
grade += "+";
}
}
else if(score >= 80) {
grade = "B";
if(score >=85) {
grade += "+";}
}
else if(score >= 70) {
grade = "C";
if(score >=75) {
grade += "+";}
}
else if(score >= 60) {
grade = "D";
if(score >=65) {
grade += "+";}
}
else{
grade = "F";
}
}
else {
System.out.println("잘못 된 범위의 점수를 입력하였습니다.");
return;
}
System.out.println("당신의 점수는 " + score + "점이고, 등급은 " + grade + "입니다");
}
}
3) Switch
import java.util.Scanner;
public class C_Switch {
//switch문도 if문과 같은 조건문이지만
//if문은 조건식(범위)을 지정했으나 switch문은 조건값을 지정(동등 비교)
public void method1() {
//1~3 사이의 정수를 입력 받아
// 1 -> 빨간색
// 2 -> 파란색
// 3 -> 초록색입니다 출력
// 잘못입력한 경우 "잘못 입력하였습니다"출력
Scanner sc = new Scanner(System.in);
System.out.print("정수 : ");
int num = sc.nextInt();
switch(num) {
case 1 :
System.out.println("빨간색입니다");
break;
case 2 :
System.out.println("파란색입니다");
break;
case 3 :
System.out.println("초록색입니다");
break;
default :
System.out.println("잘못 입력하셨습니다");
//만약 break가 거려있으면 1번 실행시 2, 3, 4의 결과값이 다 나온다
}
}
public void method2() {
Scanner sc = new Scanner(System.in);
System.out.print("과일 이름을 입력하시오 : ");
String fruit = sc.next();
int price = 0;
//0은 초기화된다는 뜻
//지역 변수는 초기화 되어야 함!!
switch(fruit) {
case "사과" :
price = 1000;
break;
case "바나나" :
price = 3000;
break;
case "복숭아" :
price = 2000;
break;
case "키위" :
price = 4000;
break;
default :
System.out.println("판매하지 않는 과일입니다");
return;
}
System.out.println(fruit + "의 가격은 " + price + "원 입니다.");
}
public void method3() {
//break가 없는 switch문을 사용한는 예
Scanner sc = new Scanner(System.in);
System.out.print("회원 등급 입력(1, 2, 3) : ");
int level = sc.nextInt();
if(level == 3) {
System.out.println("매니저 등급입니다");
}else if (level == 2) {
System.out.println("일반 회원 등급입니다");
}else {
System.out.println("신입 회원 등급입니다");
}
switch(level) {
case 3 :
System.out.println("게시글 관리 권한이 있습니다");
case 2 :
System.out.println("게시글 쓰기 권한이 있습니다");
case 1 :
System.out.println("게시글 읽기 권한이 있습니다");
}
//break 문법을 쓰지 않았을 때의 효과를 알아볼 수 있다.
//누적되어 표시문이 나오도록 할 수 있음
}
public void method4() {
//1월부터 12월까지 입력 받아 해당하는 달의 마지막 날짜를 출력
//28/29일, 30일, 31일인 달로 나누어 짐
Scanner sc = new Scanner(System.in);
System.out.print("1~12월 중 하나를 입력하세요 : ");
int month = sc.nextInt();
switch(month) {
case 1 :
case 3 :
case 5 :
case 7 :
case 8 :
case 10 :
case 12 :
System.out.println(month + "월은 31일까지 입니다");
break;
case 4 :
case 6 :
case 9 :
case 11 :
System.out.println(month + "월은 30일까지 입니다");
break;
case 2 :
System.out.println(month + "월은 28일 또는 29일까지 입니다");
break;
default :
System.out.println("반드시 1~12월 사이의 값을 입력해야 합니다");
}
}
}
package com.kh.chap01.run;
import com.kh.chap01.condition.A_If;
import com.kh.chap01.condition.B_Else;
import com.kh.chap01.condition.C_Switch;
public class Run {
public static void main(String[] args) {
A_If a = new A_If();
a.method13();
//B_Else b = new B_Else();
//b.method6();
//C_Switch c = new C_Switch();
//c.method4();
}
}
'웹개발 수업 > JAVA' 카테고리의 다른 글
[Day +7]분기문 (0) | 2021.07.11 |
---|---|
[Day +6]반복문 (0) | 2021.07.11 |
[Day +4] 연산자 (0) | 2021.07.11 |
[Day +3] 선언과 초기화, 형변환, 데이터 오버플로우, printf, escape문자 (0) | 2021.07.11 |
[Day +2] 이클립스 기본 설정, 변수, 자료형, Scanner 사용법 (0) | 2021.07.11 |