JAVA

[JAVA]조건문

로돌씨 2024. 2. 13. 22:42
while 조건문:
조건에따라 반복횟수를 결정해야할때에 주로 사용 ,
조건식이 true일 경우에 계속해서 반복하는 문법이다. 조건식이 false가되면 반복을 멈추고 while문을 종료한다.

 

예제

public class WhileTest01 {
	public void testwhile() {
		int i = 1;
		while (i < 10) {
			System.out.println(i + "번째 반복문 수행");
			i++;

		}
		System.out.println("while 종료 후 i: " + i);
	}

	public void testwhile02() {
		int i = 0;
		String str = "abcdef";
		while (i < 6) {
			char ch = str.charAt(i);
			// abcdef에서 1은 b이다 (0부터 a가 시작하기때문)
			System.out.println(i + ":" + ch);
			i++;

		}
	}

	public void testwhile03() {
		int i = 1;
		while (true) // 계속 반복시켜주기위해
		{
			System.out.println(i);
			i++;

			if (i == 10) {
				break;
			}
		}
		System.out.println("종료후 i" + i);
	}

	public void testwhile04() {
		// 키보드로 4를 입력 받을때까지 반복
		// 4가 입력되면 while 종료
		Scanner sc = new Scanner(System.in);
		while (true) {
			System.out.print("숫자를 입력하세요.");
			int num = sc.nextInt();

			if (num == 4) {

				System.out.println("프로그램을 종료합니다.");
				break;
			}
		}
	}
	public void testwhile05 () {
		Scanner sc = new Scanner(System.in);
		//1부터 입력받은 수 까지 정수들의 합을 구하며 출력
		System.out.println("정수를 입력하세요.");
		int num = sc.nextInt(); 
		int sum = 0;
		
		int i = 1;
		while ( i <= num ){
			sum += i; //sum = sum+1;
			i++; 
		}
		System.out.println("sum: " + sum);
		
		
	}

}

 

 

더보기

Do while : do를먼저 실행한 뒤 while실행

public class WhileTest02 {
	public void testDoWhile() {
		// do while과 while의 차이는 do hwile의 경우에는 do를 일단 먼저 실행함
		int i = 1;
		do {
			System.out.println(i);
			i++; // i는 계속 증가한다. 를 나타냄
		} while (i <= 10); // i의 값이 10 이상이 될때까지
		System.out.println("종료후 i값 :  " + i);

	}

	public void testDoWhile2() {
		Scanner sc = new Scanner(System.in);
		String str = null ;
		do 
		{
			System.out.print("문자열 입력: ");
			str = sc.next();
			
		}while(!str.equals("out")); 
		//do while 에는 세미콜론 필요
		//입력한 문자열이 out 아니면 반복 종료
		//'문자열(str)' 사용할때에 '같다'='.equals' -> 트루 펄스값으로 나눠 트루일시 반복
		// out이 아닐때에 반복 종료를 해야하기때문에 str앞에 !를붙혀 반대로 행동하게 됨 
			
	}
}

-> do while예제

더보기

while 안에 제어문 넣기

public class WhileTest03 {
	public static void main(String[] args) {
		// While문 활용
//1. 1~100까지의 숫자를 역순으로 출력.
		prn01();
		// 2. 1~100까지의 숫자중 2의 배수만 출력.
		prn02();
		// 3. 1~100까지의 숫자 중 7의 배수의 갯수와 총합을 출력
		prn03();
	}

	public static void prn01() {
		int i = 100;
		do {
			System.out.println(i);
			i--;
		} while (i >= 1);
	}

	public static void prn02() {
		int i = 1;
		while (i <= 100) {
			if (i % 2 == 0) {
				System.out.println(i);
			}
			i++;
		}
	}

	public static void prn03() {
		int i = 1;
		int sum = 0;
		int cnt = 0;
		while(i<=100) {
			if(i % 7 == 0){
				System.out.println(i);
			
				sum += i;
				cnt ++ ;}
				i ++ ;
			
			
			}System.out.println("배수의 갯수 : " + cnt + " , 배수의 총합: "+ sum );
		}
		
	}
for문 :
for문은 
반복횟수를 명확히 알고 있을때에 주로 사용한다. 
for ( 초기화식 ; 조건식 ; 증감식 ) {
실행문장;
} 으로 사용, 조건식이 false이면 for문을 종료한다. 

 

public class ForTest02 {
	public static void main(String[] args) {
//testFor1();
		// testFor2();
		//testFor3();
		 testFor4();
	}

	public static void testFor1() {
		for (int i = 0; i < 10; i++) {
			for (int j = 0; j < 10; j++) {
				System.out.println("i=" + i + ", j=" + j);
			}
			System.out.println();
		}

	}

	public static void testFor2() {
		// 구구단 2단부터 9단까지 출력
		for (int i = 2; i < 10; i++) {
			for (int j = 1; j < 10; j++) {
				System.out.println(i + " * " + j + " = " + (i * j));

			}
			System.out.println();
			// 중첩하며 for를 사용하면 경우의수가 기하급수적으로 늘어남!
		}
	}

	public static void testFor3() {
		// 다양한 형태로 출력하기
		for (int i = 0; i < 5; i++) {
			for (int j = 0; j < 5; j++) {
				System.out.print("* ");
			}
			System.out.println();
		}
	}

	public static void testFor4() {
		Scanner sc = new Scanner(System.in);
		System.out.print("줄 수를 입력하세요.");
		int i2 = sc.nextInt();
		System.out.print("칸 수를 입력하세요.");
		int j2 = sc.nextInt();
		// 한 줄에 별표 문자를 입력된 줄 수와 칸수 만큼출력
		// 단 , 줄수와 칸수가 일치하는 위치에는 줄 번호에 대한 점수가 출력
		for (int i = 0; i < i2; i++) {
			for (int j = 0; j < j2; j++) {

				if (j == i) {
					System.out.print(j+1);
				} else {
					System.out.print("* ");
				}
			}
			System.out.println();
		} 

	}
}

for문 예제

 

public class ForTest02 {
	public static void main(String[] args) {
//testFor1();
		// testFor2();
		//testFor3();
		 testFor4();
	}

	public static void testFor1() {
		for (int i = 0; i < 10; i++) {
			for (int j = 0; j < 10; j++) {
				System.out.println("i=" + i + ", j=" + j);
			}
			System.out.println();
		}

	}

	public static void testFor2() {
		// 구구단 2단부터 9단까지 출력
		for (int i = 2; i < 10; i++) {
			for (int j = 1; j < 10; j++) {
				System.out.println(i + " * " + j + " = " + (i * j));

			}
			System.out.println();
			// 중첩하며 for를 사용하면 경우의수가 기하급수적으로 늘어남!
		}
	}

	public static void testFor3() {
		// 다양한 형태로 출력하기
		for (int i = 0; i < 5; i++) {
			for (int j = 0; j < 5; j++) {
				System.out.print("* ");
			}
			System.out.println();
		}
	}

	public static void testFor4() {
		Scanner sc = new Scanner(System.in);
		System.out.print("줄 수를 입력하세요.");
		int i2 = sc.nextInt();
		System.out.print("칸 수를 입력하세요.");
		int j2 = sc.nextInt();
		// 한 줄에 별표 문자를 입력된 줄 수와 칸수 만큼출력
		// 단 , 줄수와 칸수가 일치하는 위치에는 줄 번호에 대한 점수가 출력
		for (int i = 0; i < i2; i++) {
			for (int j = 0; j < j2; j++) {

				if (j == i) {
					System.out.print(j+1);
				} else {
					System.out.print("* ");
				}
			}
			System.out.println();
		} 

	}
}

예제 2

package com.silsub1.example;

import java.util.Scanner;

public class ForWhile {
	Scanner sc = new Scanner(System.in);

	public void printStar() {
		/*
		 * [문제 1] : 정수를 하나 입력받아, 그 수가 양수일 때만 입력된 수를 줄 수로 적용하여 다음과 같이 출력되게 함 - if문과 이중
		 * for문 사용 - 메소드명 : public void printStar1(){} ex> 정수 하나 입력 : 5 1 2 3 4 5
		 * ================ 정수 하나 입력 : -5 양수가 아닙니다.
		 */
		System.out.print("정수하나 입력:");
		int no = sc.nextInt();
		if (no >= 0) {
			for (int i = 0; i < no; i++) {
				for (int j = 0; j < no; j++) {

					if (j == i) {
						System.out.print(j+1);
						break;
					} else {
						System.out.print(" * ");
					}
				}
				System.out.println();
			} 
		} else {
			System.out.println(no + " 는 양수가 아닙니다.");
		}
	}
	public void printStar2() {
		
		System.out.print("정수를 입력하세요.");
		int no = sc.nextInt();
		String str = sc.nextLine();
		if( no > 0) {
			//바깥쪽 포 문이 줄 수를 결정 
			for (int i = 0 ; i < no+1 ; i++) {
				for (int j = 0 ; j <no +1 ; j++) {
					//같은줄  , 칸을 출력했음 
					if (j==i) {System.out.println() ;
					break;
					// -> 줄수와 칸수가 같아질때 , 식을 중지한다.
						
					}else {System.out.print("*");
				}
			}
			}}
			
		
		if( no < 0) {
			for (int i = -no ; i >= 0 ; i--) {
				for (int j = 0 ; j <= i  ; j++) {
					if (i == j) {System.out.println(); // i 와 j 가 같아졌을때 줄을 바꿔라 .
					break;
						
					}else {System.out.print("*"); 
				
			}
		}
		}
			
		}
		 if( no == 0 ){
			System.out.println("출력 기능이 없습니다.");
			// 맨위의 이프문 괄호안에 else를 작성해 사용할수도 있음 
		}
	}


/*[문제 2]
: 정수를 하나 입력받아, 양수일 때와 0일때 음수일 때 각각 
아래와 같이 출력되게 함.
- if문과 for문 사용
- 메소드명 : public void printStar2(){}
ex>
정수 입력 : 5
*
**
***
****
*****
================
정수 입력 : -5
*****
****
***
**
*
================
정수 입력 : 0
출력 기능이 없습니다.
*/
	public void countInputCharacter(){
		Scanner sc = new Scanner(System.in);
		System.out.print("문자열 입력 : ");
		String str = sc.next();
		//1.영문자인지 검사 
		for(int i = 0; i > str.length(); i++) {
			char ch = sc.next().charAt(i);
			if(!((ch >='a' && ch <='z')||(ch>='A' && ch<='Z'))) {
			// ' 만약 ch(입력받은 값)가  소문자거나 대문자일때에 '를 '!'로 부정
			// ->즉영문자가 아닐때에 
				System.out.print("영문자가 아닙니다.");
				return; //끝냄
			}
		}System.out.print("문자 입력: ");
		char ch = sc.next().charAt(0);
		int count = 0; //카운트 할 변수를 만들어줌
		for (int i =0; i<str.length(); i++) {
			if ( ch == str.charAt(i)) {
				count ++ ;
		//.2 갯수
	}
}
System.out.println("포함된 갯수 : " + count + "개");

for while문 예제

 

거의 받아쓰기만하는 고릴라로 수업듣고 집와서 부랴부랴 검색하며 이해하느라 애썼다 정말......

'JAVA' 카테고리의 다른 글

[JAVA]객체지향 프로그래밍  (0) 2024.02.19
[JAVA]배열  (0) 2024.02.14
[JAVA]제어문  (0) 2024.02.08
[JAVA] 연산자  (0) 2024.02.04
[JAVA]강제 형변환 , 접근 제한자  (0) 2024.02.02