날아라쩡글이의 블로그입니다.

Random class 본문

중앙 HTA (2106기) story/java API story

Random class

날아라쩡글이 2021. 10. 8. 05:20
반응형

자연수의 범위에서 난수를 발생시키고 싶을 때에는 math.random보다는 

Random객체가 더 편하다. 

  • for(int i =1; i <= 5; i++)일 경우 
  • double randomNumber = Math.random();   0.0<= 값의 범위 <1.0
  • Random random = new Random();
  •  double randomNumber = random.nextDouble(); 0.0 <= 값의 범위< 1.0

정수 

  • int randomNumber = Random.nextInt();
  • int의 최소값 <= 값의 범위 <= int의 최대값
  • 매개변수의 자리에 값을 넣지 않아서 int의 최소값~ int의 최대값으로 출력된다. 
  • Random.nextInt(6) //0<=값의 범위 <=bound   bound  = 6    0, 1, 2, 3, 4, 5
  • Random.nextInt(6)+1 // 0+1<=값의 범위<=bound + 1//값을 조절함. bound = 6  1, 2, 3, 4, 5, 6

로또 번호 만들기 

  • public class RandomSample2{
  • public static void main(String[]args){
  • Random random = new Random();
  • //중복을 허용하지 않는 Set으로 입력한다. 
  • Set<Integer> numbers = new TreeSet<>();//오름차순 배열이 되는 TreeSet으로 설정하면 깔끔하다.
  • while(true) {
  • if(number.size() == 6) {//size가 6이되면 
  • break; //탈출한다. 
  • }
  • int number = random.nextInt(45)+1; //1~45사이의 값을 출력한다. 
  • number.add(number); //중복되는 값은 입력하지 않는다. 
  • }
  • System.out.println(numbers); //Set의 값을 출력한다. 
반응형
Comments