본문 바로가기

자바 JAVA

간단한 번호추첨 프로그램 작성 예제 - 자바 기초

  문제) 정수 10개를 저장할 수 있는 배열을 선언하고, 0~9까지 초기화 한후, 랜덤으로(100번발생) 0~9 발생시켜 배열값의 위치를 변경하여 출력하는 프로그램 

출력예)

0123456789
5827164930 (랜덤값)
package sample;

public class Sample
{
	public static void main(String[] args)
	{
		int[] a = new int[10];
		int i, n, tmp = 0;

		for( i=0; i<a.length; i++)
		{
			a[i] = i;
			System.out.print(a[i]);
		}

		System.out.println();

		for( i=0; i<100; i++)
		{
			n = (int)(Math.random()*10);

			tmp = a[0];
			a[0] = a[n];
			a[n] = tmp;
		}

		for( i=0; i<a.length; i++)
		{
			System.out.print(a[i]);
		}
	}
}

  문제) 1~45중에 6개 번호를 추출하는 로또번호발생기 프로그램

배열의 크기를 45로 선언하고 값은 1~45까지 저장
해당 배열을 이용해서 배열인덱스 0~5번까지의 값을 랜덤함수를 이용해서 배열값을 교환한후 로또번호는 배열 0~5번째 인덱스값으로 추출하여 나타내는 프로그램 

출력예)

ball[0] : 40
ball[1] : 12
ball[2] : 19
ball[3] : 39
ball[4] : 29
ball[5] : 3
package sample;

public class Sample
{
	public static void main(String[] args)
	{
		int[] ball = new int[45];
		int i, n, tmp;

		for( i=0; i<ball.length; i++)
		{
			ball[i] = i+1;
		}

		for( i=0; i<6; i++)
		{
			n = (int)(Math.random()*45);

			tmp = ball[i];
			ball[i] = ball[n];
			ball[n] = tmp;
		}

		for( i=0; i<6; i++)
		{
			System.out.println("ball[" + i + "] : " + ball[i]);
		}
	}
}