본문 바로가기
Java

자바 반복문(Java Loop)

by wanttosleep1111 2023. 1. 16.

자바 반복문(Java Loop)

 

어떤 조건에 만족할 때까지 같은 처리를 반복하여 실행하는 구조

 


 

1. while문

 

▶ 예제

키보드로부터 입력 받은 수가 10보다 작을 때만 계속 정수를 입력 받기

10보다 큰 수를 입력하면 "종료되었습니다." 출력

package onlyPractice;

import java.util.Scanner;

public class onlyPractice {

	public static void main(String[] args) {

		
		Scanner sc = new Scanner(System.in);
		
		int num = 0;
		
		while (num < 10) {
			System.out.print("정수 입력 >> ");
			num = sc.nextInt();
			
		}
		System.out.println("종료되었습니다.");
		
	}

}

 

▶ 예제

키보드로부터 입력 받은 수를 누적하여 출력하기

-1을 입력한 경우 프로그램 종료

package onlyPractice;

import java.util.Scanner;

public class onlyPractice {

	public static void main(String[] args) {

		
		Scanner sc = new Scanner(System.in);
		
		int num = 0;
		int sum = 0;
		
		while (num != -1) {
			System.out.print("정수 입력 : ");
			num = sc.nextInt();
			
			sum += num;
			
			System.out.println("누적 결과 : "+sum);
		}
		System.out.println("종료되었습니다.");
	}

}

 

▶ 예제

숫자를 입력 받아 홀수와 짝수가 각각 몇 개 입력되었는지 출력하기

-1을 입력한 경우 프로그램 종료

package onlyPractice;

import java.util.Scanner;

public class onlyPractice {

	public static void main(String[] args) {

		
		Scanner sc = new Scanner(System.in);
		
		int num = 0;
		int odd = 0;
		int even = 0;	
		
		while (num != -1) {
			System.out.print("정수 입력 >> ");
			num = sc.nextInt();
			
			if (num%2 == 0) {
				even++;
			} else if (num%2 == 1) {
				odd++;
			} else if (num == -1) {
				break;
			}
			System.out.println("홀수 개수 : "+odd);
			System.out.println("짝수 개수 : "+even);
		}
		System.out.println("종료되었습니다.");
		
	}

}

 


 

2. do-while문

 

▶ 예제

현재 몸무게와 목표 몸무게 입력 받기

주차별 감량 몸무게 입력 받기

현재 몸무게가 목표 몸무게에 달성되면 축하한다는 문구를 출력하고 종료

package onlyPractice;

import java.util.Scanner;

public class onlyPractice {

	public static void main(String[] args) {

		
		Scanner sc = new Scanner(System.in);
		
		System.out.print("현재 몸무게 : ");
		int now = sc.nextInt();
		System.out.print("목표 몸무게 : ");
		int goal = sc.nextInt();
		int week = 0;
		
		do {
			week++;
			System.out.print(week+"주차 감량 몸무게 : ");
			int kg = sc.nextInt();
			now -= kg;
			
		} while (now > goal);
		
		System.out.println(now+"kg 달성!! 축하합니다!!");
		
		
	}

}

 

▶ 예제

plus game

랜덤으로 정수 2개를 뽑아 문제를 출력

사용자로부터 두 수의 합을 입력 받기

입력 받은 값이 두 수의 합과 일치하면 "성공", 그렇지 않은 경우 "실패" 출력

일치하지 않았을 때만 다시 실행할 것인지 물어보고 "Y"를 입력하면 계속 실행, "N"을 입력하면 종료

 

※ 자바 랜덤 정수 만들기

Random rd = new Random();

int num = rd.nextInt();

package onlyPractice;

import java.util.Random;
import java.util.Scanner;

public class onlyPractice {

	public static void main(String[] args) {

		
		Random rd = new Random();
		Scanner sc = new Scanner(System.in);
		int num1 = 0;
		int num2 = 0;
		int answer = 0;
		
		do {
			num1 = rd.nextInt(10)+1;
			num2 = rd.nextInt(10)+1;
			
			System.out.print(num1+"+"+num2+"=");
			answer = sc.nextInt();
			
			String con = "";
			
			if (num1+num2 != answer) {
				System.out.println("Fail");
				System.out.print("계속하시겠습니까? (Y,N) >> ");
				con = sc.next();
				
				if (con.equals("Y")) {
					answer = num1+num2;
				}
			} else if (num1+num2 == answer) {
				System.out.println("Success");
			}
			
			
		} while (num1+num2 == answer);
		System.out.println("종료합니다.");
		
	}

}

 

▶ 예제

로그인 프로그램

아이디와 비밀번호를 입력 받고, test//test1234 와 일치할 경우에 "로그인 성공!", 일치하지 않을 경우 "로그인 실패!" 출력

로그인에 실패했을 경우 계속 아이디와 비밀번호를 입력하고, 로그인 성공이면 종료

3번 이상 로그인 실패인 경우, "아이디와 비밀번호가 3회 틀렸습니다"라는 문장을 출력하고 종료

package onlyPractice;

import java.util.Scanner;

public class onlyPractice {

	public static void main(String[] args) {

		
		Scanner sc = new Scanner(System.in);
		
		String user_id = "test";
		String user_pw = "test1234";
		int count = 0;
		
		do {
			System.out.print("아이디를 입력하세요 : ");
			String id = sc.next();
			System.out.print("비밀번호를 입력하세요 : ");
			String pw = sc.next();
			
			if ((user_id.equals(id))&&(user_pw.equals(pw))) {
				System.out.println("로그인 성공!");
				break;
			} else {
				System.out.println("로그인 실패..!");
				count++;
			}
			
			if (count >= 3) {
				System.out.println("아이디와 비밀번호가 3회 틀렸습니다.");
				break;
			}
			
		} while (true);
		
	}
}

 

▶ 예제

1부터 100 사이의 랜덤 숫자를 생성하기

사용자로부터 숫자를 입력 받고 입력한 숫자가 더 작다면 " 더 큰 수를 입력하세요", 입력한 숫자가 더 크다면 "더 작은 수를 입력하세요" 출력하기

정답을 맞출 때까지 반복하기

package onlyPractice;

import java.util.Random;
import java.util.Scanner;

public class onlyPractice {

	public static void main(String[] args) {

		
		Scanner sc = new Scanner(System.in);
		
		Random rd = new Random();
		
		int rdNum = rd.nextInt(100)+1;
		
		do {
			System.out.print("1과 100사이의 정수를 입력하세요 >> ");
			int num = sc.nextInt();
			
			if (rdNum == num) {
				System.out.println(num+" 정답입니다.");
				break;
			} else if (rdNum < num) {
				System.out.println("더 작은 수로 다시 시도해보세요.");
			} else if (rdNum > num) {				
				System.out.println("더 큰 수로 다시 시도해보세요.");  
			}
			
		} while (true);
	}
}

 


 

3. for문

 

▶ 예제

for문을 사용하여 96에서 73까지 홀수들만 출력하기

package onlyPractice;

import java.util.Scanner;

public class onlyPractice {

	public static void main(String[] args) {

		
		Scanner sc = new Scanner(System.in);
	
		for (int i = 96; i >= 73; i--) {
			if (i%2!=0) {
				System.out.print(i+" ");
			}
		}
	
	}
}

 

▶ 예제

구구단

원하는 단과 어느 수까지 출력할 건지 입력 받아 구구단을 출력

package onlyPractice;

import java.util.Scanner;

public class onlyPractice {

	public static void main(String[] args) {

		
		Scanner sc = new Scanner(System.in);
	
		System.out.print("단 입력 : ");
		int num1 = sc.nextInt();
		System.out.print("어느 수까지 출력 : ");
		int num2 = sc.nextInt();
		
		for (int i = 1; i<=num2; i++ ) {
			System.out.println(num1+"*"+i+"="+num1*i);
		}
	
	}
}

 

▶ 예제

약수 구하기

입력 받은 정수의 약수를 구하기 (임의의 숫자로 나누었을 때 나머지가 0이라면 약수)

package onlyPractice;

import java.util.Scanner;

public class onlyPractice {

	public static void main(String[] args) {

		
		Scanner sc = new Scanner(System.in);
	
		System.out.print("정수 입력 : ");
		int num = sc.nextInt();
		
		for (int i = 1; i<=num; i++) {
			if (num%i == 0) {
				System.out.print(i+" ");
			}
		}
	
	}
}

 

▶ 예제

(77*1)+(76*2)+(75*3)+...+(1*77)을 계산하여 결과 출력

package onlyPractice;

import java.util.Scanner;

public class onlyPractice {

	public static void main(String[] args) {

		int result = 0;
		for (int i = 1; i <= 77; i++) {
			result += (78-i)*i;
		}
		System.out.println(result);
	}
}

 

 

▶ 예제

별찍기

package onlyPractice;

import java.util.Scanner;

public class onlyPractice {

	public static void main(String[] args) {

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

 

package onlyPractice;

import java.util.Scanner;

public class onlyPractice {

	public static void main(String[] args) {

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

 

package onlyPractice;

import java.util.Scanner;

public class onlyPractice {

	public static void main(String[] args) {

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

 

package onlyPractice;

import java.util.Scanner;

public class onlyPractice {

	public static void main(String[] args) {

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

 

package onlyPractice;

import java.util.Scanner;

public class onlyPractice {

	public static void main(String[] args) {

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

'Java' 카테고리의 다른 글

자바 이차원 배열(Java Two-dimensional array)  (0) 2023.01.22
자바 배열 (Java Array)  (0) 2023.01.17
자바 조건문(Java Conditional Statement)  (0) 2023.01.09
자바 연산자(Java Operator)  (0) 2023.01.08
자바 변수 (Java Variables)  (1) 2023.01.08

댓글