반응형
로또 프로그램 만들기
1~45번 숫자가 랜덤으로 6개 찍히게 하기
콘솔창에 결과가 찍히는 로또프로그램을 만들어보았습니다.
랜덤의 확률로 6개의 문자가 찍히도록 하였고, 각 문자가 찍힌 후에는 쓰레드를 이용하여 약 1초간 정지 후에 다시 프로그램이 작동하도록 하였습니다.
그리고 마지막에는 배열을 출력 한 후에 프로그램이 다시 반복하도록 만들었습니다.
실행화면
Girl.Java
public class Girl {
String name;
Machine machine;
public Girl(String name) {
this.name = name;
}
public void girlInfo() {
System.out.println("금주의 로또 걸은 " + name + " 입니다.");
}
public void start()
{
if(machine == null)
machine = new Machine();
machine.comeDown();
machine.ballInfo();
}
}
로또를 돌리는 Girl이라는 객체를 만들어 보았습니다.
start() 메서드를 통해서 Machine객체에서 기능이 실행되게 됩니다.
Machine.java
import java.util.Arrays;
import java.util.Random;
@SuppressWarnings("serial")
public class Machine extends Random {
int[] ball = new int[6];
boolean check = true;
public int nextInt(int max) {
return super.nextInt(max) + 1;
}
//랜덤으로 45 숫자 뽑기
public int run() {
int num = this.nextInt(45);
return num;
}
//중복 체크
public boolean check(int num) {
for (int i = 0; i < ball.length; i++) {
if (ball[i] == num) {
check = false;
break;
} else {
check = true;
}
}
return check;
}
//중복 체크 후 배열에 값 넣기
public void comeDown() {
for (int i = 0; i < ball.length; i++) {
int num = run();
if (check(num)) {
ball[i] = num;
System.out.println((i + 1) + "번 공은 " + num + " 입니다.");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else {
i--;
}
}
}
//배열 전체 출력
public void ballInfo()
{
System.out.print("이번 주의 당첨 번호는 ");
System.out.print(Arrays.toString(ball));
System.out.println("입니다. 축하드립니다~");
}
}
대부분의 기능이 machine에서 실행되게 됩니다.
특히 run()메서드에서 임의의 숫자 1~45의 결과값이 출력되어서
배열에 들어가게 됩니다.
Menu.java
import java.util.Scanner;
public class Menu {
public String Select() {
System.out.println("시작 하려면 아무 키나 눌려주세요.");
@SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
String key = sc.nextLine();
return key;
}
}
Program.java
public class Program {
public static void main(String[] args) {
/*
* 로또 프로그램을 작성하시오.
*/
Girl hong = new Girl("홍진영");
Menu menu = new Menu();
while (true) {
String key = menu.Select();
if (key != null) {
hong.girlInfo();
hong.start();
}
}
}
}
이상 자바를 이용한 로또 프로그램입니다.
728x90
반응형