<λ‚œμˆ˜ λ°œμƒ μ‹œν‚€κΈ°>

1.Random 클래슀의 객체λ₯Ό 생성

2. 객체λͺ….nextInt(μ •μˆ˜) 0 λΆ€ν„° μ •μˆ˜-1 사이에 λ¬΄μž‘μœ„ 수λ₯Ό 1개 λ°œμƒμ‹œν‚¨λ‹€.

3. 1~μ •μˆ˜ 사이에 λ‚œμˆ˜λ₯Ό λ°œμƒ μ‹œν‚€κ³  μ‹ΆμœΌλ©΄ 객체λͺ….nextInt(μ •μˆ˜)+1

   - 객체λͺ….nextInt(μ •μˆ˜+1) μ•„λ‹˜.

 

 

β—‹ Random 예제

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
import java.util.Scanner;
import java.util.Random;
public class Test90{
    public static void main(String[] args){
 
        //Scanner μΈμŠ€ν„΄μŠ€ μƒμ„±
        Scanner sc = new Scanner(System.in);
 
        //μ•ˆλ‚΄ λ©”μ„Έμ§€ μΆœλ ₯
        System.out.print("λ°œμƒμ‹œν‚¬ λ‚œμˆ˜μ˜ κ°―수 μž…λ ₯:");
        int size = sc.nextInt();
 
        //size λ³€μˆ˜μ— λ‹΄μ•„λ‚Έ μˆ˜ λ§ŒνΌμ˜ λ°°μ—΄λ°© λ§Œλ“€κΈ°.
        //(λ°°μ—΄ μ„ μ–Έ λ° λ©”λͺ¨λ¦¬ ν• λ‹Ή)
        int[] arr = new int [size];
 
        Random rd = new Random();
 
        //System.out.println("λ°œμƒν•œ λ‚œμˆ˜:" + rd.nextInt(10));        
        //0~~9κΉŒμ§€ μ‚¬μ΄μ— λ‚œμˆ˜
 
        for(int i=0;i<size; i++){
 
            arr[i]=rd.nextInt(100)+1;
            //rd.nextInt(100)      => 0 ~ 99 κ°€μ§€μ˜ λ¬΄μž‘μœ„ μ •μˆ˜ ν•œκ°œ λ°œμƒ
            //rd.nextInt(100)+1    => 1 ~ 100 κΉŒμ§€μ˜ λ¬΄μž‘μœ„ μ •μˆ˜ ν•œκ°œ λ°œμƒ
        }
 
        for(int i=0; i<size; i++){
            System.out.print(arr[i]+" ");
        }
        System.out.println();
 
 
cs

λ¬Έμž₯1,17) λ¬΄μž‘μœ„ 숫자λ₯Ό λ°œμƒ μ‹œν‚€κΈ° μœ„ν•΄μ„œλŠ” λ‚œμˆ˜ λ°œμƒ μ „μš© 객체가 ν•„μš”ν•˜λ‹€.

              import java.util.Random; 

              - Random 클래슀의 nextInt(int n)λ©”μ†Œλ“œ 

              - 0 ~ λ§€κ°œλ³€μˆ˜λ‘œ λ„˜κ²¨λ°›μ€ μ •μˆ˜ n-1κΉŒμ§€μ˜ 수 쀑 λ¬΄μž‘μœ„ 숫자 1개λ₯Ό λ°œμƒμ‹œν‚¨λ‹€.

λ¬Έμž₯ 25) 0~99κΉŒμ§€μ˜ λ¬΄μž‘μœ„ μ •μˆ˜ ν•œκ°œ λ°œμƒ

λ¬Έμž₯ 26) 1~100κΉŒμ§€μ˜ λ¬΄μž‘μœ„ μ •μˆ˜ ν•œκ°œ λ°œμƒ

 

 

 

+ Recent posts