[ java ] 로또 번호 가져오기 1-45 랜덤 숫자 > java

본문 바로가기
사이트 내 전체검색

java

[ java ] 로또 번호 가져오기 1-45 랜덤 숫자

작성자 웹지기
작성일 20-12-12 15:41 | 조회 8,774 | 댓글 0

본문

1-45의 랜덤 숫자 불러오기

일반적으로 랜덤 숫자를 불러오게 되면 중복이 발생한다

아래 구문은 기본적으로 6개의 랜덤 숫자를 불러들인다. 

import java.util.Random;


public class Question1 {

    public static void main(String[] args) {

        //중복없이 숫자를 뽑는 로또 프로그램

        Random rand = new Random();

        

        int[] arr = new int[6];

        

        for(int i=0; i<6; i++) {

            arr[i] = rand.nextInt(45)+1;

        }

        for(int i : arr) { //foreach로 사용

            System.out.println("행운의 숫자 : "+i);

        }

        /*

        for(int i=0; i<6; i++) { //for로 사용

            System.out.println(" 행운의 숫자 : "+arr[i]);

        }

        */

    }

 

이 구문을 여러번 반복하다 보면 같은 숫자가 나오는 경우가 생긴다.

중복 되는 구문을 제거 해 주기위해 다중 for 문을 써줘야 한다.


import java.util.Random;

 

public class Question1 {

    public static void main(String[] args) {

        //중복없이 숫자를 뽑는 로또 프로그램

        Random rand = new Random();

        

        int[] arr = new int[6];

        

        for(int i=0; i<6; i++) {

            arr[i] = rand.nextInt(45)+1;


            //랜덤을 돌리면 중복된 숫자 발생

            //중복제거

            for(int j=0; j<i; j++) {

                if(arr[i] == arr[j]) {

                    i--;

                }

            }

        }

        

        for(int i=0; i<6; i++) {

            System.out.println(" 행운의 숫자 : "+arr[i]);

        }

    }

}

 

0 0

댓글목록 0

등록된 댓글이 없습니다.

java 목록

Total 113
게시물 검색

회원로그인

접속자집계

오늘
19,865
어제
24,727
최대
61,067
전체
18,017,192

그누보드5
Copyright © funyphp.com. All rights reserved.