프로그래밍/Java 공부

for문(별찍기), switch문, while문, do~while문

개발계발게발 2021. 5. 24. 17:23
반응형

 

for문 구구단

public class For05 {
	public static void main(String[] args) {
		for (int i = 1; i <= 10; i += 2) {
			System.out.println(i); // 1,3,5,7,9
		}
		int val = 0;
		for (int i = 1; i <= 5; i++) {
			// System.out.println("반복문");
			for (int j = 1; j <= 5; j++) {
				val++;
				System.out.println(val + "번 반복했습니다.");
			}
		}

		for (int i = 0; i < 5; i++) {
			for (int j = 0; j < 5; j++) {
				System.out.print("*");
			}
			System.out.println("");
		}

		// 구구단 2~9단

		// 2단
		A:for (int i = 2; i < 10; i++) {
			B:for (int j = 1; j < 10; j++) {
				// if(j % 3 == 0) { // 2 * 3, 2 * 6, 2 * 9....
				if (j % 3 == 2) {
					//break; // 가장 가까운 반복문 탈출.
					continue A; // A반복문으로
					//라벨문
					//중첩된 반복문에서 이름을 지정 가능
					//필요에 따라서 해당 이름을 가진 반복문을 탈출하거나 제어 가능	
				}
				System.out.println(i + " X " + j + " = " + (i * j));
			}
		}
		System.out.println("");
	}
}

 

업다운 게임

 

// 랜덤한 숫자 두자리수를 뽑고 사용자가 숫자를 입력하면
// UP/ DOWN을 출력하고
// 일치하면 "축하합니다"라고 하면서 출력/ 종료하는 프로그램

 

import java.util.Scanner;

public class For06 {
	public static void main(String[] args) {
		int ran = (int) ((Math.random() * 99) + 1);
		Scanner sc = new Scanner(System.in);
		int input = 0;
		for (int i = 0; i < 20; i++) {
			System.out.println("숫자를 입력하세요.1~99\t 남은 횟수 : " + (20 - i));
			input = sc.nextInt();

			if (ran == input) { // 숫자 동일
				System.out.println("축하합니다.");
				break;
			}
			else if(ran > input) { // 컴퓨터 숫자가 클 경우
				System.out.println("UP");				
			}
			else { // 컴퓨터 숫자가 작을 경우
				System.out.println("DOWN");
			}
		}
		sc.close();
	}
}

 

for문 별찍기

기본 별찍기, 리버스 별찍기

 

public class For07 {
	public static void main(String[] args) {
		//기본 별
//		  *
//		  **
//		  ***
//		  ****
//		  *****	
		for (int i = 0; i < 5; i++) { // 줄
			for (int j = 0; j < i+1 ; j++) { // 별
				System.out.print("*");
			}
			System.out.println("");
		}
		System.out.println("");

		for (int i = 10; i > 0; i--) {
			System.out.println(i);
		}
		
		//리버스 별
//		****
//		***
//		**
//		*
		for (int i = 0; i < 5; i++) {
			for (int j = 5; j > i; j--) {
				System.out.print("*");
			}
			System.out.println("");
		}

		for (int i = 5; i > 0; i--) {
			for (int j = 0; j < i; j++) {
				System.out.print("*");
			}
			System.out.println("");
		}		
	}
}

 

피라미드 별찍기, 영문자(N) 별찍기, 마름모 별찍기

 

import java.util.Scanner;
public class For07 {
	public static void main(String[] args) {

		// 영문자 N
//		*   *
//		**  *
//		* * *
//		*  **
//		*   *
		Scanner sc = new Scanner(System.in);
		System.out.println("홀수를 입력하세요.");
		int input = sc.nextInt();
		
		if(input%2==0) {
			input++;		}		
		
		for (int i = 0; i < input; i++) {
			for (int j = 0; j < input; j++) {
				if (j == 0 || j == input-1 || i == j) {
					System.out.print("*");
				} else {
					System.out.print(" ");
				}
			}
			System.out.println("");
		}
		//마름모
//		____*
//		___***
//		__*****
//		_*******
//		*********
//		_*******
//		__*****
//		___***
//		____*
		System.out.println("숫자를 입력하세요.");
		input = sc.nextInt();
		for (int i = 0; i < input; i++) {		//상단
			for (int j = input-1; j > i; j--) {
				System.out.print("_");
			}
			for (int j = 0; j < i * 2 + 1; j++) {
				System.out.print("*");
			}
			System.out.println("");
		}
		for (int i = input-1; i > 0; i--) {		//하단
			for (int j = input; j > i; j--) {
				System.out.print("_");
			}
			for (int j = 1; j < i * 2; j++) {
				System.out.print("*");
			}
			System.out.println("");
		}
	}
}

 

 

switch문, 스위치문

switch~case문

 

if와 else~if의 또 다른 형태
각조건을 case의 값과 비교해서 결과가 true이면 조건을 빠져나간다.
switch의 조건 값의 타입은 수치형일 경우는 int이하만 가능
문자열도 조건 값으로 가능

 

/*
   switch(검색변수){
    case 조건:
    조건이 true일때 실행할 문장;
    break;
    case 조건2:
    조건2가 true일때 실행할 문장;
    break;
    default :
    나열된 case의 조건이 모두 false일때
    기본적으로 실행되는문장;
    break;
   
    ※주의※ 검색 변수는 int타입 이하
    long, 실수형 사용불가
 */

public class Switch01 {
	public static void main(String[] args) {
		// int number = 'A';
		// String number1 = "Hi";
		
		int number = 6;

		switch (number) {
		case 0:
		case 1:
			System.out.println("number는 0입니다.");
			break;
			
		case 5:
			System.out.println("number는 5입니다.");
			break;
						
		default:			
			System.out.println("number는 0과 5가 아닙니다.");
			break;
		}
	}
}

 

직급별 층수

 

public class Switch02 {
	public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);
		System.out.println("당신의 직급을 입력하세요.");
		System.out.println("1.사장 \t 2.부장 \t 3.과장 \t 4.대리 \t 5.사원 \t 6.알바");
		
		int input = sc.nextInt();
		
		System.out.println("올라갈 수 있는 층은?");
		switch(input) {
		case 1:
			System.out.println("6층");
			break;
		case 2:
			System.out.println("5층");
			break;
		case 3:
			System.out.println("4층");
			break;
		case 4:
			System.out.println("3층");
			break;
		case 5:
			System.out.println("2층");
			break;
		case 6:
			System.out.println("1층");
			break;			
		default:
			break;			
		}		
	}
}

 

성별코드로 남녀 구별 및 출생년도 구별

 

import java.util.Scanner;
//성별코드를 입력받고 몇년도에 태어난 성별이 무엇인지 출력
public class Switch03 {
	public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);
		System.out.print("주민등록번호 중 성별 코드 입력 _ ");
		
		int year=0, code;	//년도, 성별코드
		String sex ="";	//성별을 저장;
		code = sc.nextInt();
		
		switch (code) {
		case 1:
		case 2:
			year = 1900;
			break;
		case 3:			
		case 4:
			year = 2000;
			break;
		default:
			System.out.println("잘못 입력했습니다.");
			System.exit(0); // 프로그램 종료
		}
		
		sex = (code % 2 == 0) ? "여성" : "남성";
		//		조건식		  ?	 	참 : 거짓;
		
		System.out.println("당신은 "+ year + "년도에 태어난");
		System.out.println(sex + "입니다.");
		//if문과 같다
		//key 값이 일치한 case만 실행하고 나간다(break 필수)
		//범위를 지정할 수 없다.
		//
	}
}

 

while

무한 반복문

while(조건식){
 조건식이 참이면 계속 실행
}

while은 보통 무한 반복을 실행하다가 특정 조건이 되면 탈출

채팅, 게임 등 무한 반복 로직에서 활용

 

public class While01 {
	public static void main(String[] args) throws IOException {
		
		boolean exit = true;
		
		while(exit) {
			System.out.println("조건식이 참이면 돕니다.");
			System.out.println("멈출까요?(Y/N)");
			char input =(char) System.in.read();
			System.in.read();// 엔터도 == \n \r
			System.in.read();// 엔터키 처리
			
			if(input == 'Y' || input == 'y') {
				exit = !exit;
				System.out.println("종료합니다.");
			}
		}
		System.out.println("while문 아래 출력문");		
	}
}

 

while문 사용 업/다운 게임

 

import java.util.Scanner;

public class While03 {
	public static void main(String[] args) {
		
		int ran = (int) (Math.random()*99+1);
		int cnt=0;
		Scanner sc = new Scanner(System.in);
		
		while (true) {
			cnt++;
			System.out.println("숫자를 입력하세요. " +cnt+"번째 시도");
			int input = sc.nextInt();
			if(ran == input) {
				System.out.println("축하합니다.");
				break;
				}
			else if(ran > input) {
				System.out.println("UP");
			}
			else {
				System.out.println("DOWN");				
			}
		}
		sc.close();
	}
}

 

do~while문

do {
조건식이 참일때 실행할 문장;
} while (조건식);

 

do~while문은 while문과 다르게 조건식이 거짓이여도 무조건 한번은 실행

public class Dowhile01 {
	public static void main(String[] args) {
		do {
			System.out.println("조건식이 거짓이라도 무조건 한 번은 실행");
		} while (false);
	}
}

 

do~while문 활용

Ex -점수 입력받기

import java.util.Scanner;

public class Dowhile01 {
	public static void main(String[] args) {
		int java, jsp, total;
		double avg;
		char grade;		
		Scanner sc = new Scanner(System.in);		
		//점수 입력받기		
		do {
			System.out.println("자바 점수를 입력하세요.");
			java = sc.nextInt();			
		}while(java < 0 || java > 100);
		do {
			System.out.println("jsp 점수를 입력하세요.");
			jsp = sc.nextInt();			
		}while(jsp < 0 || jsp > 100);
		
		total = java+jsp;
		avg= (double)total/2;
		switch((int)avg/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("JAVA 점수 : "+java+" JSP 점수 : "+jsp);
		System.out.println("총점은 "+total+"점 평균은 : "+ avg+"점으로 학점은 "+grade+"입니다.");
        System.out.printf("JAVA 점수 : %3d",java);
		System.out.printf("평균 : %.2f",avg);
        /*
		 * 		정수 %d --> %자릿수d   --> 20을 3%d로 출력하면 -> _20
		 * 		실수 %f --> %자릿수f   --> 2.000을 %.2f로 출력 -> 2.00
		 */
	}
}

 

 

반응형

'프로그래밍 > Java 공부' 카테고리의 다른 글

배열, 이차원 배열  (0) 2021.05.26
배열, foreach문  (0) 2021.05.25
조건문(if), 반복문(for)  (0) 2021.05.21
연산자, 조건문(if, else if)  (0) 2021.05.20
변수, 데이터 타입, 형변환  (0) 2021.05.19