I have a lottery program that I would like to ask me to take a guess at the 'winning' numbers and then will generate said numbers. When it's done, it will print those numbers back to me, and tell me how many tries it took to arrive at the correct answer.
My code is below. I thought I'd gotten the answer from another thread, was so sure that I closed it - and can't find it now. My question is really just a 'What's wrong with my code?' type, as I think that the code is working, but since the array is 6 numbers I figure it will take the computer some time.
For that reason, I changed the array to just 1 number and it was still taking forever to come back with a "You guessed it in...!" Leading me to believe there is something else wrong I'm missing.
package lottery;
import java.util.Scanner;
public class lottery { // Begin lottery class
public static void main(String[] args) { // Begin MAIN method
// Define variables
Scanner keyboard = new Scanner(System.in);
int[] lottery = new int[6];
int randomNum = 1 + (int) Math.random() * 59;
int noTimes = 1;
int guess = 0;
// End variable definition
System.out.println("Generating lottery numbers, what is your guess?");
while (guess != randomNum) {
guess = keyboard.nextInt();
guess++;
}
// Input received - generate numbers now
System.out.println("Thank you. Generating lottery numbers now...");
for (int i = 0; i < 6; i++) {
randomNum = (int) Math.ceil(Math.random() * 59); // Random number created here.
for (int x = 0; x < i; x++) {
if (lottery[x] == randomNum) // Here, code checks if same random number generated before.
{
randomNum = (int) Math.ceil(Math.random() * 59);// If random number is same, another number generated.
x = -1; // restart the loop
}
}
lottery[i] = randomNum;
}
for (int j = 0; j < noTimes; j++) {
for (int i = 0; i < lottery.length; i++) {
System.out.print("The winning numbers are: " + lottery[i] + " ");
}
System.out.println("\n");
System.out.print("You correctly guessed in " + guess + " tries.");
}
} // End MAIN method
} // End Lottery class
Apparently, I don't know how to do the regular code tag? colors?
There are various problems in your code, which are explained below.
To generate a random integer between 1 and 59 inclusive (but not 60), please use the following code snippet in your 3 places:
int randomNum = 1 + (int)(Math.random() * 59);
The guess-check logic needs to be fixed (as outlined below):
int noTimes = 0; // Corrected
...
while (guess != randomNum) {
guess = keyboard.nextInt();
noTimes++; // Corrected
}
The last pair of for-loops (the ones just before the 3 consecutive prints) look weird. Here is a more sensible replacement:
System.out.print("The winning numbers are:");
for (int i = 0; i < lottery.length; i++) {
System.out.print(" " + lottery[i]);
}
System.out.println();
System.out.println("You correctly guessed in " + noTimes+ " tries.");
Other than these, your code looks okay to me so far.
PS: Choosing 6 ordered items from 59 elements has 32.4 billion possibilities.
Related
To explain about the program that I am making, it is program that asks the user how many times he would like his coin to flip. In this program, the coin of the head is even, and the odd is the tail.
I created a script that randomizes numbers from 1 to 10 based on the number you entered. And also I've made the script that how many odd and even numbers had come out, but I don't know how to make a script that shows how many times do each of the 10 random numbers occur and which number occurred most often.
Here is the script that I have made:
import java.util.*;
public class GreatCoinFlipping {
public static void main(String[] args) {
System.out.println("How many times do you want to flip the coin? : ");
Scanner sc = new Scanner(System.in);
int amount = sc.nextInt();
int[] arrNum = new int[amount];
int even = 0, odd = 0;
for (int i = 0; i < amount ; i++) {
arrNum[i] = (int)(Math.random() * 10 + 1);
System.out.println(arrNum[i]);
if (arrNum[i] % 2 == 0) even++;
else odd++;
}//end for
System.out.println("Head: " + even + ", Tail: " + odd);
}//end main
}//end class
What I am expecting on this script that that I want to make the script that shows how many times do each of the 10 random numbers occur and which number occurred most often and I want to make it by the count method. But the ramdon number part has to be in array method. Can someone please help me with this problem?
The arrNum variable will contain an array of all occurences of each number. So if you want to count, for example, how many times 4 occurred in this, you can do this:
Arrays.stream(arrNum).filter(n -> n == 4).count()
For 7 you can do this:
Arrays.stream(arrNum).filter(n -> n == 7).count()
And you can do the same for other digits (1 to 10).
This would be a simple/straight-forward way of doing it. You can also improve it by creating a method that returns this count:
public static int getCount(int[] arr, int num) {
return Arrays.stream(arr).filter(n -> n == num).count();
}
And then call this in a loop:
for(int i=1; i<=10; i++) {
System.out.println("Count for " + i + ": " + getCount(arrNum, i));
}
To keep track of the random number you generate you can use a array. The array starts out as all 0's and is of size 10 (because there are 10 numbers between 0-9).
int size = 10;
int numbers_counter[] = new int[size];
// initialize the values
for(int i = 0; i < size; i++){
numbers_counter[i] = 0;
}
// count some random numbers
for(int i = 0; i < 100; i++){
numbers_counter[(int)(Math.random() * size)] += 1;
}
// print how many times each number accured
for(int i = 0; i < size; i++){
System.out.println("" + i + " occured: " + numbers_counter[i] + " times");
}
You can apply this method to your code.
I need to program a lottery simulator and basically everything works fine but I have one small problem at the end of the problem. There are 2 Arrays(i need to work without Array Lists) which get compared. The generated winning numbers and the numbers entered by the user. I succeeded in showing what numbers are the right guesses. But what doesn't work is showing HOW MANY guesses were correct. I tried System.out.println("You guessed this many numbers right: "+intArray.length[i] but this didn't work. Is there any way to show the exact number of how many numbers were guessed right? Thanks for any help in advance
for (int i=0; i< intArray.length;i++){
for (int j=0; j< ownArray.length;j++){
if (intArray[i] == ownArray[j]){
System.out.println("Your following guess was correct: "+intArray[i]);
Just use a count variable
public static void main(String[] args) {
int[] intArray = {1,2,4,5};
int[] ownArray = {1,0,2,7};
int count = 0;
System.out.println("Your following guesses were correct: ");
for (int i = 0; i < intArray.length; i++){
for (int j = 0; j < ownArray.length; j++){
if (intArray[i] == ownArray[j]){
System.out.print(intArray[i] + " ");
count++;
}
}
}
System.out.println("\nNo. of correct guesses: " + count);
}
Output:
Your following guesses were correct:
1 2
No. of correct guesses: 2
This is actually quite simple to do if your lottery numbers are positive numbers. It is more involved if the numbers can be negative. The basic algorithm is to compare lottery numbers one by one against all the player's guesses repeatedly. If there is a match then we record -1 in the user guess array and increment a counter to track the number of correct entries.
Some code will make this clearer:
public class LotteryNumbers {
public static void main(String[] args) {
int[] lotteryNumbers = {1,2,3,4,5,6};
int[] userGuess = {1,2,3,4,8,9};
int correct = 0;
for(int i=0; i<lotteryNumbers.length; i++) {
for(int j=0; j<userGuess.length; j++) {
if( userGuess[j] == lotteryNumbers[i]) {
userGuess[j] = -1; // 'eliminate' this guess for checking
correct++;
break;
}
}
}
System.out.println("Number of correct numbers = " + correct);
}
}
Outputs:
Number of correct numbers = 4
This works because the algorithm strikes out matches in the player's guesses and guards against future matching next time through the loop. You can imagine that what we are actually doing is striking off numbers in the player's guess that match against the lottery numbers.
I have to do an 'instant lottery' program in my first computer science class. All semester my professor has read verbatim from the book, so now I am a little lost, truthfully. I know how to do most of it, but am just having trouble figuring out array sort and how to compare user input and the random number output. My professor refuses to answer questions about take home assignments and has banned the use of anything except: arrays, loops and math.random- so no sets or anything more complex that could help. I've seen other programs that compile, but all with sets.
I have the code for user input of the lottery numbers and to generate the output of the random numbers. I can most likely also figure out how to print the payout with if/else. I just need to know how to get the program to compare the numbers an figure out if the user is a "winner" or not.
import java.util.Scanner;
public class TheLottery {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in); //user input of their lottery numbers
System.out.print("Enter number 1: ");
int num1 = keyboard.nextInt();
System.out.print("Enter number 2: ");
int num2 = keyboard.nextInt();
System.out.print("Enter number 3: ");
int num3 = keyboard.nextInt();
System.out.print("Enter number 4: ");
int num4 = keyboard.nextInt();
System.out.print("Enter number 5: ");
int num5 = keyboard.nextInt();
System.out.print("Enter number 6: ");
int num6 = keyboard.nextInt();
}
int[] lottery = new int[6];
int randomNum;
{
for (int i = 0; i < 6; i++) {
randomNum = (int) (Math.random() * 50); // Random number created here.
for (int x = 0; x < i; x++) {
if (lottery[x] == randomNum) // Here, code checks if same random number generated before.
{
randomNum = (int) (Math.random() * 50);// If random number is same, another number generated.
x = -1; // restart the loop
}
}
lottery[i] = randomNum;
}
for (int i = 0; i < lottery.length; i++)
System.out.print(lottery[i] + " "); //print random numbers
}
}
the final program should have the user enter 6 numbers, the program compare the numbers for matches, figure out if the user is a 'winner', show the prize and an added thing is show how much they spent (each 'ticket' is $1) vs how much they won. So far all that outputs is the scanner and random numbers
It looks like you obtained six numbers then didn't use them. Your lottery array is automatically initialized to zero. I think you're trying to compare an array with inputs to a random array, so you need a loop to put your entered values into. After you do that, initialize your random array, then just compare the arrays.
public static void main(System[] args) {
Scanner in = new Scanner(System.in);
int[] lottery = new int[6];
System.out.println("Enter " + lottery.length + " numbers: ");
for (int i = 0; i < lottery.length; i++) {
lottery[i] = in.nextInt();
}
The specific question has to do with how to do the comparison and figuring a "winner". It isn't clear what makes the definition of "winner".
Based upon my comment, and as shown in the answer by #szoore, I would use an array to collect the input. I'd use a method to collect (since one can change to use a different method for the selections, which makes testing easier).
/**
* Obtain the specified number of entries from the user
*/
public static int[] getUserSelections(final int numSelections)
{
Scanner in = new Scanner(System.in);
// read N entries from the user
int[] nums = new int[numSelections];
// NOTE: no error processing in this loop; should be refined
// bad numbers (e.g., negative, too large), duplicate entries, etc.
// need to be removed
for (int i = 0; i < numSelections; ++i) {
System.out.print("Enter number " + (i + 1) + ": ");
nums[i] = in.nextInt();
}
return nums;
}
The OP has a basic generation for the lottery numbers, but again I'd use a method. This has a slight refinement to the duplicate check, by using a method, and also allows the same duplicate check method to be later used for checking matches:
public static int[] getLotteryNumbers(final int numSelections)
{
// the largest number to be selected; all numbers between
// 1 and maxNum (inclusive) will have equal(-ish) probability
// of being generated
final int maxNum = 50;
int[] lottery = new int[numSelections];
Random rnd = new Random();
// make N random selections, and ensure we don't have duplicates
for (int i = 0; i < numSelections; ++i) {
boolean generate = true;
while (generate) {
int sel = rnd.nextInt(maxNum) + 1;
generate = numberInArray(sel, lottery);
if (! generate) {
lottery[i] = sel;
}
}
}
return lottery;
}
/**
* Returns true if the specific queryNum is found in the pastSelections
* Could be slightly optimized by passing how many selections have
* already been made
*/
public static boolean numberInArray(int queryNum, int[] pastSelections)
{
// look at each element and see if already there; exit via return
// if so
for (int i = 0; i < pastSelections.length; ++i) {
if (pastSelections[i] == queryNum) {
return true;
}
}
return false;
}
The use of the method 'numberInArray' then allows for fairly easy check on how many numbers match:
// see how many match
int matches = 0;
// see if the user entry exists in the lottery; if so, we
// have a match
for (int i = 0; i < userEntries.length; ++i) {
if (numberInArray(userEntries[i], lottery)) {
++matches;
}
}
System.out.printf("Found %2d matches%n", matches);
Determining payouts, etc. is straight forwarding using if/else or (perhaps better) a switch based on the number of matches.
Also, the entries and lottery selections should probably be sorted. It isn't clear if the built-in sort may be used or not. Write the sort method as appropriate:
/**
* Sorts the array; implement sorting as needed
*/
public static void sort(int[] arr)
{
Arrays.sort(arr);
}
/*
* outputs the array if one cannot use Arrays.toString(arr)
*/
public static void outputArray(int[] arr)
{
for (int i = 0; i < arr.length; ++i) {
System.out.printf("%2d ", arr[i]);
}
System.out.println();
}
Sample main:
public static void main(String[] args)
{
// how many options for the lottery; here it is 6
final int numEntries = 6;
// this method obtains from user
int[] userEntries;
userEntries = getUserSelections(numEntries);
sort(userEntries);
// display User selections
outputArray(userEntries);
int[] lottery = getLotteryNumbers(numEntries);
sort(lottery);
// display lottery numbers
outputArray(lottery);
// see how many match
int matches = 0;
// see if the user entry exists in the lottery; if so, we
// have a match
for (int i = 0; i < userEntries.length; ++i) {
if (numberInArray(userEntries[i], lottery)) {
++matches;
}
}
System.out.printf("Found %2d matches%n", matches);
//
// TODO: calculate winnings based upon the number of matches
//
}
Having difficulty trying to write code for this problem above. Please find the code below. Have to read in 5 numbers and compute the frequency of positive numbers entered.
import java.util.Scanner;
public class Lab02Ex2PartB {
public static void main (String [] args){
Scanner input = new Scanner(System.in);
System.out.println("Please enter a positive integer");
int number = input.nextInt();
for(int i = -2 ; i < 4 ; i++)
System.out.println("Positive Count is: " + i);
}
}
Your problem is that you have a task that needs to be repeated (about the user entering a value); but your loop (the perfect mean to do things repeatedly) ... doesn't cover that part!
for(int i=-2 ; i<4 ; i++)
System.out.println("Positive Count is: " +i);
Instead, do something like:
for (int loops = 0; loops < 5; loops++) {
int number = input.nextInt();
Then of course, you need to remember those 5 values, the easiest way there: use an array; Turning your code into:
int loopCount = 5;
int numbers[] = new[loopCount];
for (int loops = 0; loops < loopCount; loops++) {
numbers[loops] = input.nextInt();
And then, finally, when you asked for all numbers, then you check the data you got in your array to compute frequencies. A simple approach would work like this:
for (int number : numbers) {
if (number > 0) {
System.out.println("Frequency for " + number + " is: " + computeFrequency(number, numbers));
}
with a little helper method:
private int computeFrequency(int number, int allNumbers[]) {
...
Please note: this is meant to get you going - I don't intend to do all your homework for you. You should still sit down yourself and figure what "computing the frequency" actually means; and how to do that.
Try this one, Remember if you only want to know the frequency(not storing)
import java.util.Scanner;
public class Lab02Ex2PartB {
public static void main (String [] args){
int i = 1;// is a counter for the loop
int positive =0;// counts positive numbers
while(i<=5){
Scanner input = new Scanner(System.in);
System.out.println("Please enter a whole positive number");
int number = input.nextInt();
if(number > 0){
positive ++;
}
i++;
}
System.out.println("Positive Count is: "+ positive);
So... I have a bit of a problem in a lab. I've been at it for a while, but my program just isn't doing what I'm expecting it to do. I'm currently writing a Sieve of Eratosthenes program in Java. Unfortunately, it's not giving the expected output of a list of primes. I can't, for the life of me, figure out what's wrong... Could anyone here give me a pointer as to where I might have messed something up?
Much thanks!
import java.util.*;
import java.math.*;
public class primeSieve {
/**
* #param args
*/
public static void main(String[] args){
// TODO Auto-generated method stub
Scanner kb = new Scanner(System.in);
//Get user input
System.out.println("Please enter the first number of the set of numbers to calculate primes (first number MUST be prime):");
int first = kb.nextInt();
System.out.println("Please enter the last number of the set of numbers to calculate primes (first number MUST be prime):");
int last = kb.nextInt();
List<Integer> primeList = new ArrayList<Integer>();
List<Integer> numList = new ArrayList<Integer>();
//Make array with values from 2 to the last value entered by user
for(int i = 2; i <= last; i++){
numList.add(i);
}
int size = numList.size();
//Calculate primes
for(int i = 0; i < size; i++)
{
if(i != 0 && i % 2 == 0){continue;} //No point in checking even numbers
if(numList.get(i) == 0){continue;} //If a value has been removed, it's been set to 0. No need to check it.
int prime = numList.get(i); //The current number being worked on. Should be prime
primeList.add(prime); //The number is prime, put it into the prime list.
for(int j = prime; j < size; j += prime) //Loop to remove multiples
{
numList.set(j, 0); //Number is a multiple of the prime previously calculated. Set it to 0, not a prime.
}
}
int primeSize = primeList.size();
System.out.println(primeSize);
System.out.println("The prime numbers from " + first + " to " + last + " are:");
for(int i = first; i < primeSize; i++)
{
System.out.println(primeList.get(i));
}
}
}
Edit: The output for the program when I look for primes between 2 and 50 is this:
The prime numbers from 2 to 50 are:
7
13
19
25
31
39
43
49
In the nested for loop, you start j at prime. However, consider the prime 2: it is at index 0, not index 2. Things should work out if you start j at prime-first. Also, as a commenter pointed out, your print loop should start at index 0 rather than first.