Study Web Development

11월 1일

이전으로

자바

4. 제어문

for

  1. 새 클래스 ForMain05 생성
public class ForMain05 {
	public static void main(String[] args) {
		// 다중 for문
		for(int dan=2;dan<=9;dan++) { // 단
			System.out.println("** " + dan + "단 **");
			for(int i=1;i<=9;i++) { // 곱해지는 수
				System.out.println(dan + " * " + i + " = " + dan*i);
			}
		}
	}
}

while

  1. 새 클래스 WhileMain01 생성
public class WhileMain01 {
	public static void main(String[] args) {
		int i=1; // 초기식 지정
		while(i<=10) { // 조건식 지정
			System.out.println(i++); // 증감식 지정; 증감식을 지정하지 않으면 무한 루프가 발생
		}
		System.out.println("========");
		int j=10;
		while(j>=0) {
			System.out.println(j--);
		}
	}
}
  1. 새 클래스 WhileMain02 생성
public class WhileMain02 {
	public static void main(String[] args) {
		int sum = 0, su = 1; // 초기식
		while(su<=100) { // 조건식
			sum+=su; // 누적
			su++; // 증감식
		}
		System.out.println("1부터 100까지의 합 = "+sum);
	}
}
  1. 새 클래스 WhileMain03 생성
public class WhileMain03 {
	public static void main(String[] args) {
		java.util.Scanner input = new java.util.Scanner(System.in);
		
		System.out.print("단 입력 : ");
		int dan = input.nextInt();
		
		System.out.println(dan + "단");
		System.out.println("========");
		
		int i = 1;
		while(i<=9) {
			System.out.println(dan + " * " + i + " = " + dan*i);
			i++;
		}
		
		input.close();
	}
}
  1. 새 클래스 WhileMain04 생성
    • 이클립스에서 main 입력 후 ctrl+space, enter 입력시 public static void main(String[] args) {}이 자동 완성
public class WhileMain04 {
	public static void main(String[] args) {
		java.util.Scanner input = new java.util.Scanner(System.in);
		
		int a, total = 0;
		System.out.println("0 전까지 입력받은 정수로 합 구하기");
		System.out.print("누적할 정수 데이터 입력 : "); // 가이드 문자열
		
		// 증감식 없이 루프를 빠져나오는 형태
		while((a = input.nextInt()) != 0) { // 입력받은 값을 a에 저장하고, a의 값이 0이 아니면 true
			total += a; // 누적
			System.out.print("누적할 정수 데이터 입력 : "); // 가이드 문자열
		}
		
		System.out.println("total = " + total); // 누적한 데이터 출력
		
		input.close();
	}
}
  1. 새 클래스 WhileMain05 생성
public class WhileMain05 {
	public static void main(String[] args) {
		java.util.Scanner input = new java.util.Scanner(System.in);
		
		int a, total = 0;
		System.out.println("0 전까지 입력받은 정수로 합 구하기");
		
		// 초기식 없이 루프를 빠져나오는 형태; 증감식 없는 형태의 경우 가이드 문자열을 2번 쓰지만 초기식 없는 형태는 1번만 쓰니 코드가 더 깔끔함
		while(true) {
			System.out.print("누적할 정수 입력 : ");
			a = input.nextInt();
			if(a == 0) {
				break; // while문 탈출
			}
			total += a; // 누적
		}
		
		System.out.println("total = " + total); // 누적한 데이터 출력
		
		input.close();
	}
}
  1. 새 클래스 WhileMain06 생성
    • 자바에서 변수를 삭제할 수는 없으며, {} 블럭 내에서 선언한 변수는 해당 블럭을 빠져나오면 소멸됨
public class WhileMain06 {
	public static void main(String[] args) {
		// 은행 프로그램
		java.util.Scanner input = new java.util.Scanner(System.in);
		
		int balance = 0; // 잔고 선언
		
		while(true) {
			System.out.println("========");
			System.out.println("1. 예금 | 2. 출금 | 3. 잔금 | 4. 종료"); // 메뉴 출력
			System.out.println("========");
			
			System.out.print("메뉴 선택 > ");
			int num = input.nextInt(); // while문 블럭 내에서만 생존하는 지역 변수로, 반복 실행되더라도 한 번만 선언한 것으로 인식함
			if(num == 1) {
				System.out.print("예금액 > ");
				balance += input.nextInt();
			}
			else if(num == 2) {
				while(true) {
					System.out.print("출금액 > ");
					int withdraw = input.nextInt();
					if(withdraw>balance) {
						System.out.println("잔금보다 더 많이 출금할 수 없습니다.");
					}
					else {
						balance -= withdraw;
						break;
					}
				}
			}
			else if(num == 3) {
				System.out.printf("잔고 : %,d원\n", balance);
			}
			else if(num == 4) {
				System.out.println("프로그램 종료");
				break;
			}
			else {
				System.out.println("잘못 입력하셨습니다.");
			}
		}
		
		input.close();
	}
}
  1. 프로젝트 ch02-operator에 새 클래스 OperatorMain12 생성
public class OperatorMain12 {
	public static void main(String[] args) {
		java.util.Scanner input = new java.util.Scanner(System.in);
		/*
		 * [실습] A전자 대리점에서는 그날 물건 판매액의 15%를 할인해 주기로 했습니다.
		 * 판매한 상품명과 상품의 단가와 수량을 키보드로부터 입력받아 지불 금액을 출력하는 프로그램을 작성하세요.
		 * (단, 출력시에는 소숫점 아래 자리를 절삭)
		 * [출력 예시]
		 * 상품명 입력 : 냉장고
		 * 단가 입력 : 500000
		 * 판매 수량 입력 : 3
		 * 냉장고 3대의 가격은 1,275,000원
		 */
		System.out.print("상품명 입력 : ");
		String item = input.next();
		System.out.print("단가 입력 : ");
		int price = input.nextInt();
		System.out.print("판매 수량 입력 : ");
		int quantity = input.nextInt();
		System.out.printf("%s %d대의 가격은 %,d원", item, quantity, (int)(price*quantity*0.85));
		input.close();
	}
}
  1. 프로젝트 ch03-operation에 새 클래스 WhileMain07 생성
public class WhileMain07 {
	public static void main(String[] args) {
		java.util.Scanner input = new java.util.Scanner(System.in);
		/*
		 * [실습] 
		 * 커피전문점에서 아메리카노가 4,000원입니다. 마실 커피 수량을 정하고 돈을 지불하세요.
		 * 지불한 돈에서 발생한 거스름돈을 출력하고, 상품의 총 비용보다 지불한 돈이 적어서 상품을 구매할 수 없을 경우 "금액이 부족합니다."라고 알려준 후 다시 지불할 수 있는 프로그램을 작성하세요.
		 * [출력 예시]
		 * 구매 수량 입력 > 2
		 * 내가 지불한 금액 > 10000
		 * 거스름돈 : 2,000원
		 * ---> 구매 종료
		 * ========
		 * 구매 수량 입력 > 2
		 * 내가 지불한 금액 > 5000
		 * 3,000원이 부족합니다.
		 * ---> 다시 구매할 수 있도록 처리
		 */
		int price=4000;
		int quantity; // 수량
		int balance; // 거스름돈
		int payment; // 지불한 금액
		int total; // 총 지불해야 할 금액
		quant: while(true) { // 수량 루프에 label 지정
			System.out.print("구매 수량 입력 > ");
			quantity=input.nextInt();
			if(quantity>0) {
				total=price*quantity;
				while(true) { // 금액 루프
					System.out.print("내가 지불한 금액 > ");
					payment=input.nextInt();
					balance=payment-total;
					if(balance>=0) {
						break; // 금액 루프 탈출
					}
					else {
						System.out.printf("%,d원이 부족합니다.\n", -balance);
						continue quant; // label이 지정된 수량 루프로 이동
					}
				}
				System.out.printf("거스름돈 : %,d원\n", balance);
				break; // 수량 루프 탈출
			}
			else {
				System.out.println("수량은 0 이하일 수 없습니다.");
			}
		}
		input.close();
	}
}

do~while

  1. 새 클래스 DoWhileMain 생성
public class DoWhileMain {
	public static void main(String[] args) {
		String str = "Hello World";
		int su = 0;
		
		while(su++ < 5) { // 5회 실행
			System.out.println(str);
		}
		
		System.out.println("========");
		
		int su2 = 0;
		
		do { // 6회 실행; do~while문에 while문과 동일한 조건식 사용할 경우, 항상 do~while문이 while문보다 한 번 더 실행하게 됨
			System.out.println(str);
		} while(su2++ < 5);
	}
}

break

  1. 새 클래스 BreakMain01 생성
public class BreakMain01 {
	public static void main(String[] args) {
		int n = 1;
		// 단일 반복문
		while(n<=10) {
			System.out.println(n);
			n++;
			if(n == 8)
				break; // 단일 루프 while문을 빠져나감
		}
	}
}
  1. 새 클래스 BreakMain02 생성
public class BreakMain02 {
	public static void main(String[] args) {
		// 다중 반복문
		for(int i=0;i<3;i++) {
			for(int j=0;j<5;j++) {
				if(j == 3)
					break; // j는 4까지 반복되지 못하고 2까지만 반복하며, i는 break 영향을 받지 않음
				System.out.println("i = " + i + ", j = " + j);
			}
		}
	}
}
  1. 새 클래스 BreakMain03 생성
    • 이클립스에서 코드를 선택하고 ctrl+i 입력시 들여쓰기를 자동 정렬함(붙여넣기 등으로 정렬이 깨진 경우)
public class BreakMain03 {
	public static void main(String[] args) {
		// 다중 반복문에서 break label 사용
		exit_for: // label 지정
		for(int i=0;i<3;i++) {
			for(int j=0;j<5;j++) {
				if(j == 3)
					break exit_for; // break 다음에 label을 명시하면 label이 지정된 for문을 빠져나감
				System.out.println("i = " + i + ", j = " + j);
			}
		}
	}
}

continue

  1. 새 클래스 ContinueMain 생성
public class ContinueMain {
	public static void main(String[] args) {
		for(int i=0;i<=10;i++) {
			if(i%3==0) { // 3의 배수일 때 건너뜀
				continue;
			}
			System.out.println(i);
		}
	}
}
  1. 새 클래스 Score 생성
public class Score {
	public static void main(String[] args) {
		java.util.Scanner input = new java.util.Scanner(System.in);
		
		int korean, english, math, sum;
		char grade;
		float avg;
		
		do {
			System.out.print("국어 : ");
			korean = input.nextInt();
		} while(korean < 0 || korean > 100); // 0부터 100 사이의 값 입력시 false가 되어 do~while문 블럭 탈출
		
		do {
			System.out.print("영어 : ");
			english = input.nextInt();
		} while(english < 0 || english > 100);
		
		do {
			System.out.print("수학 : ");
			math = input.nextInt();
		} while(math < 0 || math > 100);
		
		sum = korean + english + math;
		                                        
		avg = sum / 3.0f;
		
		switch((int)(avg / 10)) { // 0부터 100까지를 하나하나 case로 지정하기 번거롭고, 등급은 10 단위로 결정되므로 인자값도 /10한 값을 씀
		case 10:
		case 9:
			grade = 'A'; break;
		case 8:
			grade = 'B'; break;
		case 7:
			grade = 'C'; break;
		case 6:
			grade = 'D'; break;
		default:
			grade = 'F';
		}
		
		System.out.println();
		System.out.printf("총점 : %d\n평균 : %.2f\n등급 : %c", sum, avg, grade);
		
		input.close();
	}
}

5. 배열

5-1 1차원 배열

  1. 새 자바 프로젝트 ch04-array 생성하고 새 클래스 ArrayMain01 생성
public class ArrayMain01 {
	public static void main(String[] args) {
		// 배열 선언
		char[] ch;
		// 배열 생성
		ch = new char[4]; // 배열의 주소가 저장되는 ch를 배열명이라고 함
		// 배열의 초기화
		ch[0] = 'J'; // 배열에 저장된 데이터를 배열의 요소라고 함
		ch[1] = 'a';
		ch[2] = 'v';
		ch[3] = 'a';
		
		// 배열의 요소 출력
		System.out.println(ch[0]);
		System.out.println(ch[1]);
		System.out.println(ch[2]);
		System.out.println(ch[3]);
		
		// 반복문을 이용한 배열의 요소 출력
		for(int i=0;i<ch.length;i++) { // 배열의 길이는 배열명.length로 호출함
			System.out.println("ch[" + i + "] : " + ch[i]);
		}
		
		// 배열의 선언 및 생성
		int[] it = new int[6]; // 정수형 배열의 경우 요소는 0으로 초기화되어 있음
		int it2[] = new int[6]; // 배열임을 의미하는 대괄호의 위치는 자료형 옆과 배열명 옆 모두 가능함
		
		// 배열 선언 및 생성(명시적 배열 생성), 초기화
		char[] ch2 = new char[] {'J', 'a', 'v', 'a'}; // 길이의 경우 입력한 데이터 수에 의해 자동으로 결정되며, 오히려 초기화하면서 길이를 명시하면 오류가 발생
		for (int i=0;i<ch2.length;i++) {
			System.out.println(ch2[i]);
		}
		
		// 배열 선언 및 생성(암시적 배열 생성), 초기화
		char[] ch3 = {'자','바'};
		System.out.println(ch3[0]);
		System.out.println(ch3[1]);
	}
}
  1. 새 클래스 ArrayMain02 생성
public class ArrayMain02 {
	public static void main(String[] args) {
		// 배열 선언 및 생성(암시적 배열 생성), 초기화
		int[] score = {100,88,88,100,90}; // score.length는 5로 저장됨
		int sum = 0;
		float avg = 0.0f;
		
		for(int i=0;i<score.length;i++) {
			sum += score[i];
		}
		avg = sum / (float)score.length; // 분모에 배열의 길이를 이용하게 되면, 배열에 요소를 추가하거나 삭제하더라도 분모를 수정할 필요 없음
		
		System.out.printf("총점 : %d\n평균 : %.2f", sum, avg);
	}
}

과제

  1. 프로젝트 ch03-operation에 새 클래스 IfMain07 생성
public class IfMain07 {
	public static void main(String[] args) {
		/*
		 * [실습]
		 * 생년월일을 입력하고 만 나이를 출력하는 프로그램을 작성하시오.
		 * 만 나이 = (현재 연도 - 생년) - (생일이 지났으면 0, 생일이 지나지 않았으면 1)
		 * 
		 * [출력 예시]
		 * 연도 입력 : 2001
		 * 월 입력 : 10
		 * 일 입력 : 20
		 * 만 나이는 ?
		 */
		int thisYear = 2021;
		int thisMonth = 11;
		int thisDate = 1;
		java.util.Scanner input = new java.util.Scanner(System.in);
		System.out.println("생년월일을 입력하세요.");
		
		int year, month, date;
		
		while(true) { // 연도 루프
			System.out.print("연도 입력 : ");
			year = input.nextInt();
			if(year>1900) {
				while(true) { // 월 루프
					System.out.print("월 입력 : ");
					month = input.nextInt();
					if(month>=1&&month<=12) {
						while(true) { // 일 루프
							System.out.print("일 입력 : ");
							date = input.nextInt();
							if(month==2){
								if(date>=1&&date<=28) {
									break;	
								}
								else {
									System.out.println("일은 1부터 28까지만 가능합니다.");
								}
							}
							else if((month%2==0&&month<=6)||(month%2==1&&month>=9)) {
								if(date>=1&&date<=30) {
									break;	
								}
								else {
									System.out.println("일은 1부터 30까지만 가능합니다.");
								}
							}
							else {
								if(date>=1&&date<=31) {
									break;	
								}
								else {
									System.out.println("일은 1부터 31까지만 가능합니다.");
								}
							}
						}
						break; // 월 루프 탈출
					}
					else {
						System.out.println("월은 1부터 12까지만 가능합니다.");
					}
				}
				break; // 연도 루프 탈출
			}
			else {
				System.out.println("연도를 잘못 입력하셨습니다");
			}
		}
		
		int age=thisYear-year;
		if(thisMonth<month) { // 생일 지나지 않음(월)
			age-=1;
		}
		else if(thisMonth==month) {
			if(thisDate<date) { // 생일 지나지 않음(일)
				age-=1;
			}
		}
		System.out.println("만 나이는 ? "+age);
		
		input.close();
	}
}

다음으로