Java
do-while문
soultreemk
2021. 11. 22. 09:23
- 계속진행여부 물을때
do{
// 실행문 (한번은 무조건 실행됨)
// 계속진행여부
System.out.print("계속하시겠습니까?(1:예, 2:아니오)");
int ans = scan.nextInt();
if(ans==1) continue;
else break;
}while(true);
while(true){
// 실행문
// 계속진행여부
System.out.print("계속하시겠습니까(1:예, 2:아니오)?");
int ans = sc.nextInt();
if(ans==1) continue;
else break;
}
- 예제) 로또번호 생성기
단, 보너스번호를 제외한 정렬과 중복제거도 구현해야함
import java.util.Random;
import java.util.Scanner;
public class Lotto {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Random ran = new Random();
while(true) {
System.out.print("게임수=");
int gameCount = scan.nextInt();
// 게임수만큼 반복
for(int cnt=1; cnt<=gameCount; cnt++) {
// 하나의 게임을 저장할 배열 생성
int lotto[] = new int[7];
for(int i=0; i<lotto.length; i++) {
lotto[i] = ran.nextInt(45)+1;
// 지금까지 만들어진 번호와 중복검사
// lotto[3]까지 만들었으면 [3]이랑 [0],[1],[2] 비교
// --> 중복된게 있으면 [3]을 다시 생성 (i--)
for(int check=0; check<i; check++) {
if(lotto[i]==check) i--;
}
}
// 정렬 (마지막에 생성된 보너스 제외)
for(int idx=0; idx<lotto.length-2; idx++) {
for(int j=0; j<lotto.length-2-idx; j++) {
if(lotto[j] > lotto[j+1]) {
int tmp = lotto[j];
lotto[j] = lotto[j+1];
lotto[j+1] = tmp;
}
}
}
// 출력
System.out.print(cnt+"게임=[");
for(int i=0; i<lotto.length-1; i++) {
if(i==lotto.length-2) {
System.out.print(lotto[i]+"]");
}else {
System.out.print(lotto[i]+",");
}
}
System.out.print(", bonus="+lotto[lotto.length-1]);
System.out.println();
}
// 계속진행여부
System.out.print("계속하시겠습니까?(1:예, 2:아니오)");
int ans = scan.nextInt();
if(ans==1) continue;
else break;
}
}
}
- 숫자맞추기
import java.util.Random;
import java.util.Scanner;
public class NumberMatch {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Random ran = new Random();
int ans = ran.nextInt(100)+1; // 비교할 정답으로 난수 하나 입력받기
int cnt = 0;
do {
do {
System.out.print("1~100사이의 정수 입력=");
int inData = Integer.parseInt(sc.nextLine());
//맞춘회수
cnt++;
if(ans > inData) {
System.out.println("더 큰 수 입니다.");
}else if(ans < inData) {
System.out.println("더 작은 수 입니다.");
}else {
System.out.println(cnt+"번째 맞추셨습니다.");
break;
}
}while(true);
// 종료 확인
System.out.print("계속하시겠습니까?(예:y/Y, 아니오:그외)");
String que = sc.nextLine();
if(!que.equalsIgnoreCase("y")) {
break;
}
}while(true);
}
}