[Java] While, do-While, Math.random() and Random Class

· Tech· Java
Java

While Statements and Applications


Initialization of variables;       

while (conditional expression) {

Statement to be executed repeatedly;   → When the condition is true, it is executed.

When you want to create an infinite loop in a while statement like

for(;;), you can make it a loop by putting true in place of the conditional expression. And just like the for statement, the multiplication table can be output in the while statement.

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(+@@T 134@@+loop+". while test~~");    
if(loop =@@T153@ @= 5) break;
}
          
loop=0;
while(true) { |
if(+ +loop>10) break;   //Escape Conditions
    if(loop%2 =@@T 210@@= 0continue;   //아래로 안내려가고 ()속으로
    System.out.println@@T228@ @(loop +". Hi oooooOracle~~");    
}
        
System.out.printf("%35s","==== 구구단 ====\n"); 
 
int jul= 0, dan=1;
        
while(!(+@@T 282@@+jul>9)) { //9행
    while(!(+@ @T306@@+dan>9)) { //8열
        String str = (dan@@T325 @@<9)?"\t":"\n";   //삼항연산자
        System.out.print(da n+"*"+@@T354 @@jul+”="+@ @T364@@jul*dan+str);    
    }
    dan=1;     //초기화 해주고 줄바꿈
}
cs

do-While Statements and Applications


Variable initialization;     

do{

Statement to be executed repeatedly;

​ Incremental;

} while(conditional expression);

do is executed first, and then if the condition is met, it is repeated again. 

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

Factorial n! Find the value

In other words, when performing factorial, natural numbers from 1 to n must be sequentially multiplied. 

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) {
        
        /*
            ==실행결과==
▷Start natural number: 1Enter
▷End natural number: 20 Enter
What are the prime numbers from 1 to 20?
2,3,5,7,11,13,17,19
Number of prime numbers from 1 to 20? 8
Sum of prime numbers from 1 to 20? 77
=== Program End ===
*/
| Scanner(System.in);
int startNo = @@T1 139@@0, endNo = 0;
             
               do {
try {
| ");
… startNo = sc.nextInt();
sc.nextLine();
| ");
… endNo = sc.nextInt();
sc.nextLine();
| @ @T1209@@|| endNo@@T 1215@@<1) {
                   System.out.@@T1 227@@println(">> All values you enter must be natural numbers!! <<\n");
                      } else {
sc.close();
break;
{
{@T1245@@catch (InputMismatchException e) {
                  System.out. println(">> Please enter only natural numbers!! <<\n");
sc.nextLine();    //The value must be empty to avoid infinite repetition.
                 }
           } while (true);    //I just turned it until I added a natural number
          
        String resultStr ="";
        int cnt = @@T12 91@@0, sum = 0;
         //When dividing, we check one by one to see how much the remainder is.
         for(int i@ @T1312@@=startNo; i@@T1318@ @=endNo; i@@T1325@ @++) {
| T1339@@=1) continue//1 is not prime
              
|
               
               for(int@@T1368 @@ j=2; j <i; j@@T13 81@@++) {
| @@=0) { //If i, the test target, is not a prime number, there is no need to test.
|
break;
{
                }
              
|
cnt++;    // Number of prime numbers
    // Cumulative total of prime numbers
|
| 5@@>1)?",":"";
… resultStr +@@T14 81@@= comma+i; 
                }
             }
          
         System.out.println (startNo+" to "@@T1 509@@+endNo+@@T15 What are the prime numbers up to 17@@"? "+resultStr);
         System.out.println (startNo+" to "@@T 1537@@+endNo+@@T1 What is the number of prime numbers up to 545@@"? "+cnt);
         System.out.println (startNo+" to "@@T 1565@@+endNo+@@T1 What is the sum of prime numbers up to 573@@"? "+sum);
          System.out.@@T1 587@@println("=== Program End ===");
{ }



}
cs

Math.random( ) and its applications


You can get a random real number between

0 and 1 using the Math.random() method. When you want to find a random integer, (int)Math.random()*interval range+start value; It can be obtained with If you calculate by substituting real random numbers, you can see why an expression like this is created.

//Write a code to obtain an authentication key, create an authentication key consisting of a 3-digit integer and 4 lowercase letters

// You can create random alphabet and lowercase characters by writing them in int and coercively converting them to (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@@ T1892@@ Scanner(System.in);
System.out.println("Select[1.odd/0.even] => ");    //Premise, exception handling omitted
String choice = sc.nextLine();
char ch = choice.charAt(0);  
//***0 is int 48
//To change the char type to a number, subtract '0'
int choiceNo =@ @T1946@@ ch-'0'//0 or 1
int randNo = (int)(Math.rand om()*10+1);
          
String ​result = "";
if (choiceNo =@@T1996@ @= randNo%2) {
· result = "Correct";
} else
 result = "Wrong";
System.out.@@T202 9@@println(result+@@T2 035@@" The randomly generated number is "+ra ndNo+"입니다.");    
cs

//Bingo game where the computer's random values are guessed

math.You can achieve the same effect by using the Random class instead of the random() method. In the same way as the Scanner class, a Random object is created and a random variable value is input and substituted into an integer type. At this time, rnd.nextInt(100-1@@T 2074@@+1)+1; Like (range number)+first number; You can specify the range of the random value by expressing it as:

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("== Bingo game ==\n");
Random rnd =@ @T2164@@ new Random();
int rndNum @@T2175 @@= rnd.nextInt(100-@@T2180 @@1+1)@@T 2187@@+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

Comments

No comments yet. Be the first!

    164 posts in 테크

    15 / 164