import java.util.Random; import java.util.Scanner; /** * This program picks lotto numbers for the user. 6 numbers randomly picked * between 1 and 50. The program allows the user to reject one of the numbers * and get a new value for one of the numbers repeatedly until they are feel * lucky. Then they enter -1 and the program terminates. * * This program is to review the following topics: * @review.topic arrays * @review.topic generating random numbers * @review.topic using Scanner * @review.topic && and ! * @review.topic while and for loops * @author 1997 William Lenhart; Modified 1999 Andrea Danyluk, 2003 Stephen Freund, 2006 Stacia Wyman */ public class LottoHelper { /** Upper limit on lotto number range */ public static final int MAX = 50; /** How many numbers a lotto ticket needs */ public static final int NUMS = 6; public Random picker; private int myNums[] = new int[NUMS]; /** Constructor for class initializes the array of lotto numbers */ public LottoHelper(){ picker = new Random(); for(int i = 0; i < NUMS; i++) { // nextInt() gives values between Integer.MIN_VALUE and // Integer.MAX_VALUE. Take abs value and then mod MAX to // obtain a number between 0 and 49. Add 1 to get btn 1 and MAX int nextNum = Math.abs(picker.nextInt()) % MAX + 1; myNums[i] = nextNum; } } /** Prints out the array of lotto numbers */ public void printNums(){ for (int i = 0; i < NUMS; i++){ System.out.print(myNums[i]+" "); } System.out.println(); } /** Generates a new random number to replace whatever number is in index */ public void changeNum(int index){ // another way to generate numbers between 1 and max: give MAX as arg myNums[index-1] = picker.nextInt(MAX)+1; } public static void main(String[] args) { Scanner s = new Scanner(System.in); LottoHelper myHelper = new LottoHelper(); myHelper.printNums(); System.out.println("To change one of the numbers, enter a number\n"+ "between 1 and 6. To accept, type -1."); int userInput = s.nextInt(); // User entering -1 means they like their numbers, stop execution. while (userInput != -1){ while (!(userInput > 0 && userInput < 7)){ System.out.println("Valid inputs are 1..6 or -1. Please reenter:"); userInput = s.nextInt(); } myHelper.changeNum(userInput); myHelper.printNums(); userInput = s.nextInt(); } System.out.println("Bonne chance!"); } }