java.util.Random 클래스
java.util.Random APIRandom 클래스의 객체를 생성하고 Random 클래스의 메소드를 사용하면 다양한 타입의 난수를 생성 할 수 있습니다.
| 제어자 타입 | 메소드 | 기능 |
|---|---|---|
| boolean | nextBoolean() | 유일한 값인 Boolean 난수를 생성하여 리턴합니다. |
| float | nextFloat() | 0.0~1.0 사이의 유일한 값인 float 난수를 생성하여 리턴합니다. |
| int | nextInt() | 유일한 값인 int 난수를 생성하여 리턴합니다. |
| int | nextInt(int bound) | 0부터 int bound값 사이의 int 난수를 생성하여 리턴합니다. |
구현
-
Code
Lotto.javaimport java.util.Random; public class Lotto { int[] lotto = new int[6]; Random random = new Random(); public void makeLotto(){ lotto[0] = random.nextInt(45)+1; // break문을 사용했을 경우 // for(int i=1; i<6; i++){ // int temp = random.nextInt(45)+1; // lotto[i]=temp; // for(int j=0; j<i; j++){ // if(lotto[j]==temp){ // i--; // break; // } // } // } // continue문을 사용했을 경우 for(int i=1; i<6; i++){ int temp = random.nextInt(45)+1; for(int j=0; j<i; j++){ if(lotto[j]==temp){ temp = random.nextInt(45)+1; // continue문을 만나도 j값이 1 증가 하므로 // j=0으로 하면 j가 1증가되어 j=1이 되어서 for문이 // 실행되므로 j=0일때는 비교가안됨 j=-1; continue; } lotto[i]=temp; } } for(int value: lotto){ System.out.print(" [ "+value+ " ] "); } } } -
Code
LottoMain.javapublic class IfExampleMain { public static void main(String[] args) { IfExample result =new IfExample(); result.ifStatement(); } -
Result
java.util.TreeSet 응용
java.util.TreeSet APITreeSet 클래스는 이진탐색트리(Binary Search Tree)의 구조로 데이터를 저장합니다. 이진탐색트리 중에서도 성능을 향상시킨 '레드-블랙 트리(Red-Black Tree)로 구현되어 있습니다. 따라서 데이터의 추가, 삭제시에는 추가 시간이 발생 하지만, 검색능력과 정렬능력이 높다는 장점이 있습니다. TreeSet은 중복된 데이터의 저장을 허용하지 않으므로 중복되는 번호를 허용하지 않는 번호를 호출할 때 사용할 수 있습니다.
구현
-
Code
TreeSetLotto.javaimport java.util.Random; import java.util.TreeSet; public class TreeSetLotto { public static void main(String[] args) { Random rd = new Random(); TreeSet<Integer> ts= new TreeSet<>(); while(ts.size()<6){ ts.add(rd.nextInt(45)+1); } System.out.println(ts); } } -
Result