While 문과 응용


변수의 초기화;       
   while(조건식) {            
      반복해서 실행할 명령문;   → 조건이 참일때, 실행된다.
      증감식;

 

for(;;) 와 같이 while 문에서 동일하게 무한반복문을 만들고자 할 때는 조건식 자리에 true 를 넣어 반복문으로 만들 수 있다. 그리고 for문과 동일하게 while 문에서도 구구단 출력이 가능하다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
int loop=0;
while(true) { 
    System.out.println(++loop+". while 테스트~~");    
    if(loop == 5break;
}
        
loop=0;
while(true) {  
    if(++loop>10break;   //탈출조건
    if(loop%2 == 0continue;   //아래로 안내려가고 ()속으로
    System.out.println(loop +". Hi oooooOracle~~");    
}
        
System.out.printf("%35s","=== 구구단 ===\n"); 
 
int jul=0, dan=1;
        
while(!(++jul>9)) { //9행
    while(!(++dan>9)) { //8열
        String str = (dan<9)?"\t":"\n";   //삼항연산자
        System.out.print(dan+"*"+jul+"="+jul*dan+str);    
    }
    dan=1;     //초기화 해주고 줄바꿈
}
cs

 

 

do-While 문과 응용


변수초기화;     

do{
         반복해서 실행할 명령문;
         증감식;
   } while(조건식);

 

do의 실행할 명령문을 먼저 수행하고 그 다음에 조건에 해당하면 이후에 다시 반복한다. 

 

1
2
3
4
int cnt=5, loop=0;
        do {
            System.out.println(++loop+". Hello Java");
        } while (loop<cnt);
cs

 

팩토리얼 n! 값 구하기

 

즉, 팩토리얼 수행시에는 순차적으로 1부터 n 까지의 자연수를 곱해야 한다. 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public class FactorialMain {
 
    public static void main(String[] args) {
 
        Scanner sc = new Scanner(System.in);
        do {
            try {
                System.out.print(">> 알고 싶은 팩토리얼 수 입력 => ");
                int num = Integer.parseInt(sc.nextLine());
                
                if(num<=0) {
                    System.out.println(">> 자연수만 입력하세요!!");
                    continue;
                }
                int result = 1;
                
                for(int i=5;i>0;i--) {
                    result *= i;
                }
                System.out.println(result);            
                break;
            } catch (NumberFormatException e) {
                System.out.println(">> 정수만 입력하세요!!");
            }
        } while (true);  //무한루프
        
        sc.close();
        System.out.println("\n ~~~~~~~~~ 프로그램 종료 ~~~~~~~~~~~~~");
    }
}
cs

 

소수 구하기

 

소수는 1과 자기자신 외의 값만으로만 나누어지는 수이다.

즉, 1과  음수는 될 수 없기에 먼저 제외한다. 그리고 InputMismatchException 는 정수 값이 아닌 문자 입력시에 발생할 에러를 catch 처리한다. 

 

// 시작값과 끝값 사이의 소수를 구하고 각각의 개수, 합,  전체 나열하고자 할 때의 코드를 확인하고 작성해보기

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package my.day08.b.DOWHILE;
 
import java.util.*;
 
public class PrimeNumberMain {
 
    public static void main(String[] args) {
        
        /*
            ==실행결과==
                ▷시작 자연수 : 1엔터
                ▷끝 자연수 : 20엔터 
             1 부터 20 까지의 소수는?
             2,3,5,7,11,13,17,19
    
             1부터 20 까지의 소수의 개수? 8개  
             1부터 20 까지의 소수들의 합? 77 
             
           === 프로그램 종료 ===      
       */
        Scanner sc = new Scanner(System.in);
        int startNo = 0, endNo = 0;
        
        do {
            try {
                System.out.print(" ▷시작 자연수 : ");
                startNo = sc.nextInt();
                sc.nextLine();
                
                System.out.print(" ▷끝 자연수 : ");
                endNo = sc.nextInt();
                sc.nextLine();
                
                if(startNo<1 || endNo<1) {
                    System.out.println(">> 입력하시는 값은 모두 자연수이어야 합니다!! <<\n");
                } else {    
                    sc.close();
                    break;
                }
            } catch (InputMismatchException e) {
                System.out.println(">> 자연수만 입력하세요!! <<\n");
                sc.nextLine();    //값을 비워야 무한 반복되지 않는다.
            }
        } while (true);    //자연수를 넣을 때까지 돌린 것일 뿐
        
        String resultStr ="";
        int cnt = 0, sum = 0;
        
        //나누기를 했을 때 나머지가 얼마가 되는지 일일이 검사를 한다.
        for(int i=startNo; i<=endNo; i++) {            
            if(i==1continue//1은 소수가 아니다
            
            boolean isSosu = true;
            
            for(int j=2; j<i; j++) {
                if(i%j==0) { //검사대상인 i는 소수가 아닌 경우 검사할 필요가 없다.
                    isSosu = false;
                    break;
                }
            }
            
            if(isSosu) {    // 검사대상인 i가 소수라면
                cnt++;    // 소수의 개수
                sum+=i;   // 소수들의 누적합계
                
                // 2,3,5,7,11,13,17,19
                String comma = (cnt>1)?",":"";
                resultStr += comma+i; 
            }
        }
        
        System.out.println(startNo+"부터 "+endNo+"까지의 소수는? "+resultStr);
        System.out.println(startNo+"부터 "+endNo+"까지의 소수의 개수는? "+cnt);
        System.out.println(startNo+"부터 "+endNo+"까지의 소수들의 합은? "+sum);
        
        System.out.println("=== 프로그램 종료 ===");
    }

}
 
cs

 

Math.random( )과 응용


0~1 사이의 랜덤한 실수를 가져오는 것을 Math.random( ) 메서드로 구할 수 있다. 랜덤한 정수를 구하고자 할 때는 (int)Math.random()*구간범위+시작값; 으로 구할 수 있다. 실수형 난수를 대입해서 계산해보면 왜 이와 같은 식이 만들어 지는지 알 수 있다.

 

//인증키 구하는 코드 작성, 3자리의 정수, 4자리의 영소문자로 구성된 인증키 만들기

// int로 작성하고 (char)로 강제형변환하면 영소문자 랜덤 문자를 만들 수 있다.

 

1
2
3
4
5
6
7
8
9
10
11
String key="";
        for(int i=0; i<3; i++) {
            int num = (int)(Math.random()*10);
            key += num;
        }
        for(int i=0; i<4; i++) {
            int num = (int)(Math.random()*('z'-'a'+1)+'a');
            key += (char)num;
        }
 
        System.out.println("인증키 => "+key);
cs

 

//컴퓨터의 랜덤 값이 홀수인지 짝수인지 맞추기

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Scanner sc = new Scanner(System.in);
System.out.println("선택[1.홀수/0.짝수] => ");    //전제, 예외처리 생략
String choice = sc.nextLine();
char ch = choice.charAt(0);  
//***0은 int로 48
//char 타입을 숫자로 바꾸려면 '0' 빼기
int choiceNo = ch-'0'//0 또는 1
 
int randNo = (int)(Math.random()*10+1);
        
String result = "";
if (choiceNo == randNo%2) {
    result = "맞습니다";
else
    result = "틀렸습니다";
    System.out.println(result+" 랜덤하게 나온 수는 "+randNo+"입니다.");    
cs

 

//컴퓨터의 랜덤 값이 맞추기 빙고게임

math.random() 메서드 대신 Random 클래스를 활용해서 같은 효과를 낼 수 있다. Scanner 클래스와 동일하게 Random 객체를 생성하고 랜덤 변수값을 입력받아 정수형으로 대입해준다. 이 때, rnd.nextInt(100-1+1)+1; 와 같이 (범위수)+처음수; 로 나타내 랜덤 값의 범위를 지정할 수 있다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
System.out.println("== 빙고게임 ==\n");
 
Random rnd = new Random();
int rndNum = rnd.nextInt(100-1+1)+1;
 
Scanner sc = new Scanner(System.in);
 
int cnt = 0;
 
do {
    System.out.print("숫자입력(1~100) => ");
    int inputNum = Integer.parseInt(sc.nextLine());
    cnt++;
    
    if(inputNum<rndNum) {
        System.out.println(">> "+inputNum+"보다 큰 수 입니다.");
    } else if(inputNum>rndNum) {
        System.out.println(">> "+inputNum+"보다 작은 수 입니다.");
    } else {
        System.out.println("\n>> 빙고!! "+cnt+"번만에 맞췄습니다.");
        sc.close();
        break;
    }
    
while (true);
cs

'Java' 카테고리의 다른 글

[Java] 배열, 버블정렬  (0) 2021.01.19
[Java] Random 응용, 배열  (0) 2021.01.18
[Java] For 문 응용, 다중 For문  (0) 2021.01.15
[Java] For 문, 예제  (0) 2021.01.13
[Java] Wrapper, Math 클래스와 if, switch문  (0) 2021.01.12
댓글