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

본문 바로가기

사이트 내 전체검색

java

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

작성일 20-12-12 15:41

페이지 정보

작성자 웹지기 조회 4,780회 댓글 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

댓글목록

등록된 댓글이 없습니다.

전체 113건 7 페이지

이미지 목록

게시물 검색
Copyright © 즐거운 코딩 생활 ( funyphp ). All rights reserved.
PC 버전으로 보기