I need my lottery program to count the number of times 0,1,2,3,4 or 5 numbers match after 10 runs, then display them. It is also supposed to keep track of the total jackpot by adding a certain amount to the jackpot depending on how many numbers won. My problem is that is is counting this correctly for each individual run but not for all ten runs total. here is what I have.
package assignment5;
import javax.swing.JOptionPane;
import java.util.Random;
public class assignment5
{
public static void main(String[] args)
{
for(int i = 0; i <10; i++)
{
lottery pic=new lottery();
pic.Get_player_numbers();
pic.Get_jackpot_number();
pic.Check_winner ();
pic.Write_data();
}}
}
class lottery
{
int[] picks= new int[5];
int[] cpick=new int[5];
int i;
int j,c;
int match=0;
void Get_player_numbers ()
{
int ctemp,cdupflag=0;
for(j=0;j<=4;++j)
{
//YOU DO NOT NEED THE CNUMBERFLAG
//IF YOU GENERATED THE NUMBERS CORRECLTY, THE COMPUTER WILL NOT GENERATE ONE ABOVE 99 OR LESS THAN 1
cdupflag=0;
while(cdupflag==0)
{
ctemp = (int)Math.round(Math.random()*99)+1;
cdupflag=1;
for(c=0;c<=j;++c)
{
if(ctemp==cpick[c])
{
cdupflag=0;
}
}//inner for loop
if(cdupflag==1)
cpick[j]=ctemp;
}
}
String Jackpot="User Lottery numbers are: "+"\n";
//String computer = "";
for(j=0;j<=4;++j)
{
if(j==4)
Jackpot=Jackpot+cpick[j];
else
Jackpot=Jackpot+cpick[j]+"-";
}
JOptionPane.showMessageDialog(null,Jackpot,"Output:",JOptionPane.INFORMATION_MESSAGE);
}
//void jackpot()
void Get_jackpot_number()
{
int ctemp,cdupflag=0;
for(j=0;j<=4;++j)
{
//YOU DO NOT NEED THE CNUMBERFLAG
//IF YOU GENERATED THE NUMBERS CORRECLTY, THE COMPUTER WILL NOT GENERATE ONE ABOVE 99 OR LESS THAN 1
cdupflag=0;
while(cdupflag==0)
{
ctemp = (int)Math.round(Math.random()*99)+1;
cdupflag=1;
for(c=0;c<=j;++c)
{
if(ctemp==cpick[c])
{
cdupflag=0;
}
}//inner for loop
if(cdupflag==1)
cpick[j]=ctemp;
}
}
String Jackpot="Computer Lottery numbers are: "+"\n";
//String computer = "";
for(j=0;j<=4;++j)
{
if(j==4)
Jackpot=Jackpot+cpick[j];
else
Jackpot=Jackpot+cpick[j]+"-";
}
JOptionPane.showMessageDialog(null,Jackpot,"Output:",JOptionPane.INFORMATION_MESSAGE);
}
void Check_winner ()
{
for(int i=0;i<=4;++i)
{
for(int j=0;j<=4;++j)
{
if(picks[i]==cpick[j])
{
match=match+1;
}
}
}
}
void Write_data ()
{
String print = "";
int jackpot = 2500000;
int counter0 = 0;
int counter1 = 0;
int counter2 = 0;
int counter3 = 0;
int counter4 = 0;
int counter5 = 0;
if(match==0)
{
counter0++;
print=print+"There is no match"+"\n";
print=print+"please try again "+"\n";
jackpot=jackpot+25000;
}
else
if(match==1)
{
counter1++;
print=print+"There is one match"+"\n";
print=print+"You won 100 Dollars "+"\n";
jackpot=jackpot+100000;
}
else
if(match==2)
{
counter2++;
print=print+"There are two matches"+"\n";
print=print+"You won 1,000 Dollars"+"\n";
jackpot=jackpot+250000;
}
else
if(match==3)
{
counter3++;
print=print+"There are three matches"+"\n";
print=print+"You won 10,000 Dollars "+"\n";
jackpot=jackpot+500000;
}
else
if(match==4)
{
counter4++;
print=print+"There are four matches"+"\n";
print=print+"You won 100,000 Dollars "+"\n";
jackpot=jackpot+1000000;
}
else
if(match==5)
{
counter5++;
print=print+"There are five matches"+"\n";
print=print+"You won "+jackpot+" Dollars"+"\n";
jackpot=2500000;
}
JOptionPane.showMessageDialog(null,print,"Output:",JOptionPane.INFORMATION_MESSAGE);
System.out.println("zero matchers occured " +counter0+ " times");
System.out.println("The current jackpot is " +jackpot+ "");
}
}
//end of class lottery
Firstly, I'm not sure to understand everything as your code is a little messy and uncommented, you should try to clear it, it will be easier for you to understand and to find errors.
Concerning the problems that I am seeing:
If I correctly understand you want to keep the "Jackpot" over the 10 rounds. This is not happening because in your main function you are doing
for(int i = 0; i <10; i++)
{
lottery pic = new lottery();
....
}
Therefore you are creating a NEW lottery for each run and it replace the previous lotery by an empty one at each runs. Maybe this instead would work:
lottery pic = new lottery();
for(int i = 0; i <10; i++)
{
....
}
As well be careful to your variables "match" in your lotery class. At the end of "Write_data" I would advice you to do "match = 0;" otherwise matches will not restart at 0 for each run
Related
I'm using a method to print the largest, second largest, smallest, and second smallest integers. This is what I have so far for the base:
case 1:
System.out.print("\nEnter the Limit: ");
limit = input.nextInt();
System.out.println(pairs(limit));
break;
This is the method being called so far:
// Case 1 Method : Largest and Smallest Pairs
public static String pairs(int limit) {
System.out.println("*** Largest and Smallest Pairs");
return "";
}
The actual output is to formatted like
(largest,secondlargest),(smallest,secondsmallest)
I've never used an array before, and I'm not sure how to use loops with it to find the values. How do I begin this?
Here is the complete code for my program. You can disregard the second and third case, however, I still need help with the third. I need to display all prime numbers in order. Here is the requirement: Twin Prime Numbers: This should let the user specify a limit n (I used limit instead) (if n is 1000, then consider 1
to 1000), and lists the pairs of twin primes up to n. The sample run is (3,5),(5,7),(11,13),(17,19)
The complete code:
import java.util.Scanner;
public class PatternChecker{
// The scanner is accessible for every method included
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
// Variables
int limit;
System.out.println("List of Pattern Checker problems:\n1) Largest and Smallest Pairs\n2) Patterns of Triangles\n3) Twin Prime Pairs\n4) Quit");
System.out.print("Choice: ");
int choice = input.nextInt();
// The switch statement for the variable "choice" and each case
switch (choice) {
default:
System.out.println("\n*** INVALID OPTION");
break;
case 1:
System.out.print("\nEnter the Limit: ");
limit = input.nextInt();
System.out.println(pairs(limit));
break;
case 2:
System.out.println("\nEnter the Limit: ");
limit = input.nextInt();
System.out.println(triangleOne(limit));
System.out.println(triangleTwo(limit));
System.out.println(triangleThree(limit));
System.out.println(triangleFour(limit));
break;
case 3:
System.out.println("\nEnter the Limit: ");
limit = input.nextInt();
System.out.println(primePairs(limit));
break;
case 4:
System.out.println("\n*** End");
break;
}
}
// Case 1 Method : Largest and Smallest Pairs
public static String pairs(int limit) {
System.out.println("*** Largest and Smallest Pairs");
return "";
}
// Case 2 Method: Patterns of Triangles (Triangle One)
public static String triangleOne(int limit) {
System.out.println("*** Patterns of Triangles");
for (int x = 1; x <= limit; x++) {
for (int y = 1; y <= x; y++) {
System.out.print(y + " ");
}
System.out.println();
}
return "";
}
// Case 2 Method: Patterns of Triangles (Triangle Two)
public static String triangleTwo(int limit) {
for (int x = limit; x > 0; x--) {
for (int y = 1; y <= x; y++) {
System.out.print(y + " ");
}
System.out.println();
}
return "";
}
// Case 2 Method: Patterns of Triangles (Triangle Three)
public static String triangleThree(int limit) {
for (int row = 1; row <= limit; row++) {
for (int space = (limit - row); space > 0; space--) {
System.out.print(" ");
}
for (int num = row; num > 0; num--) {
System.out.print(num + " ");
}
System.out.println();
}
return "";
}
// Case 2 Method: Patterns of Triangles (Triangle Four)
public static String triangleFour(int limit) {
for (int row = limit; row >= 0; row--) {
for (int space = (limit - row); space > 0; space--) {
System.out.print(" ");
}
for (int num = 1; num <= row; num++) {
System.out.print(num + " ");
}
System.out.println();
}
return "";
}
// Case 3 Method: Twin Prime Pairs
public static String primePairs(int limit) {
System.out.println("*** Twin Prime Numbers up to " + limit);
return "";
}
}
Ok based on the comment i have written a quick answer with arraylists. hope this helps.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class MaxMin {
private List<Integer> alist = new ArrayList<Integer>();
public static void main(String args[]) {
MaxMin maxmin = new MaxMin();
maxmin.init();
}
public void init() {
System.out.println("Welcome!!!");
readFromUser();
printUserList();
doSort();
display();
}
public void readFromUser() {
Scanner scanner = null;
try {
scanner = new Scanner(System.in);
System.out.print("Enter the total number of elements :");
Integer totalElements = scanner.nextInt();
for (int i=0;i<totalElements;i++) {
System.out.print("Enter the " + i +" number");
alist.add(scanner.nextInt());
}
}catch(Exception e) {
e.printStackTrace();
} finally {
scanner.close();
}
}
public void printUserList() {
System.out.println("user entered list is :");
System.out.println(alist);
}
public void doSort() {
Collections.sort(alist);
}
public void display() {
System.out.println("(" +alist.get(alist.size()-1)+ "," +alist.get(alist.size()-2)+ ")" + "(" +alist.get(0)+"," +alist.get(1) +")");
}
}
I hope this isn't a homework problem, but the idea is to use a loop with the array, and keep track of the largest and smallest numbers.
Start with assigning the smallest number variable to Integer.MAX_VALUE, so the first number you check will be assigned to the smallest number, because all integer values except 2^31 - 1 are smaller than Integer.MAX_VALUE, and you do that for biggest too, but with Integer.MIN_VALUE.
And then whenever you assign the biggest number again, you assign the secondBiggest variable to the "biggest" variable.
With that in mind, you just need to loop through the values of the array and check if they're larger than the biggest (in which you re-assign it) or smaller than the smallest(same thing as biggest).
int[] array = new int[]{5, 3, 4, 1, 2};
for(int i = 0; i < array.length; i++){
System.out.println(array[i]);
}
^
Example of looping through an array
I created an example for you.
First of all it generates a list of prime numbers till the limit (in this case hardcoded 100). Next it asks for all prime pairs and prints them. The pairs are stored in an ArrayList so it is very easy to get the first and the last pair.
It's not realy hard to understand so I don't know what to explain. Take a look at the code and if you have any questions feel free to ask.
import java.util.ArrayList;
public class PatternChecker {
public ArrayList<Integer> primes = new ArrayList<>();
public static void main(String[] args) {
PatternChecker pc = new PatternChecker();
pc.detectPrimes(100);
ArrayList<int[]> numbers = pc.getPairs();
System.out.println("Print all pairs: ");
numbers.stream().forEach((intA)->System.out.println(intA[0]+" / "+intA[1]));
System.out.println("Print just the greatest and the smallest pair: ");
System.out.println("("+numbers.get(0)[0]+","+numbers.get(0)[1]+")");
System.out.println("("+numbers.get(numbers.size()-1)[0]+","+numbers.get(numbers.size()-1)[1]+")");
}
public void detectPrimes(int limit) {
for(int i=2;i<limit;i++)
if(isPrime(i))
primes.add(i);
}
protected boolean isPrime(int no) {
for(int i=0;i<primes.size();i++)
if(no % primes.get(i) == 0) return false;
return true;
}
public ArrayList<int[]> getPairs() {
ArrayList<int[]> result = new ArrayList<>();
int last = primes.get(0);
for(int i=1;i<primes.size();i++) {
if(primes.get(i)==last+2) {
int[] resH = new int[2];
resH[0] = last;
resH[1] = primes.get(i);
result.add(resH);
}
last = primes.get(i);
}
return result;
}
}
I´m trying to create a simple yahtzee game where an array is filled with 5 random numbers and where the player can choose to roll specific dices again. However I cant figure out how to write the method that is supposed to replace specific numbers in the array with new random numbers and return it. Any suggestions how to approach this?
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class YatzyGame {
private final Integer NBROFDICE = 5;
private final Integer DICEMAXVALUE = 6;
Random rnd = new Random();
Scanner keyboard = new Scanner(System.in);
public void startGame() {
int[] dice = new int[NBROFDICE];
rollDice(dice);
printDice(dice);
System.out.println("Do you want to reroll any dices? " + "Y/N");
String answer = keyboard.nextLine();
if (answer.equalsIgnoreCase("y")) {
rerollDice(dice);
} else if (answer.equalsIgnoreCase("n")) {
calculateSum(dice);
} else {
System.out.println("Wrong command!");
}
}
public int[] rollDice(int[] dice) {
for (int i = 0; i < dice.length; i++) {
dice[i] = rnd.nextInt(DICEMAXVALUE) + 1;
}
return dice;
}
public int[] rerollDice(int[] dice) {
System.out.println("What dices do you want to reroll? Dices index are 0-4");
int diceToReroll = keyboard.nextInt();
// Replace the numbers at the index the user specifies with new random numbers and return the array.
}
public void printDice(int[] dices) {
System.out.println("Your dices show: " + Arrays.toString(dices));
}
public void calculateSum(int[] dices) {
int sum = 0;
for (int i : dices) {
sum += i;
}
if (sum == 30) {
System.out.println("YAHTZEE! Your total score is 50! Congratulations!");
} else
System.out.println("Your total score is: " + sum);
}
public static void main(String[] args) {
new YatzyGame().startGame();
}
}
public int[] rollDice(int[] dice) {
System.out.println("What dice do you want to reroll? Dices index are 0-4");
int diceToRoll = keyboard.nextInt();
dice[diceToRoll] = rnd.nextInt(DICEMAXVALUE) + 1;
}
Like this you can make a function:
public int[] reroll(int amountOfRerolls, int[] dices){
for(int i =0;i<dicesToReroll;i++){
this.rollDice(dices);
}
return dices;
}
This makes the programm a bit more modal since you can reuse your rollDice() method wherever you need it. Also you could expand it a bit by handing in the indexes that are allowed to be rerolled in case needed.
edit: style
I am trying to find the occurrences of all integers submitted by the user into the program and so far here's what I got. It works but I don't think it's a legit way to do it, is there any way I can try to do this without using the list[10]=9999;? Because if I don't do it, it'll show out of boundary error.
import java.util.*;
public class OccurrencesCount
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int[] list = new int[11];
//Accepting input.
System.out.print("Enter 10 integers between 1 and 100: ");
for(int i = 0;i<10;i++){
list[i] = scan.nextInt();
list[10] = 9999;
}
//Sort out the array.
Arrays.sort(list);
int count = 1;
for(int i = 1;i<11;i++){
if(list[i-1]==list[i]){
count++;
}
else{
if(count<=1){
System.out.println(list[i-1] + " occurs 1 time.");
}
else{
System.out.println(list[i-1] + " occurrs " + count + " times.");
count = 1;
}
}
}
}
}
Personally, I think this is a perfectly good solution. It means that you can deal with the last group in the same way as all others. The only change I would make is putting the line list[10] = 9999; outside the for loop (there's no reason to do it 10 times).
However, if you want to use an array of length 10, you can change the line
if(list[i-1]==list[i])
to
if(i < 10 && list[i-1]==list[i])
If you do this, you won't get an ArrayIndexOutOfBoundsException from list[i] because the expression after the && is not evaluated when i == 10.
import java.util.*;
class OccurrencesCount {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] list = new int[101];
System.out.print("Enter 10 integers between 1 and 100: ");
for(int i = 0;i<10;i++) {
int x = scan.nextInt();
list[x]++;
}
for(int i = 1; i <= 100; i++)
if(list[i] != 0)
System.out.println(i + " occurs " + list[i] + " times ");
}
}
To store count of numbers from 1 to 100 you need to use a list of 100 integers each one storing the number of occurrences of itself. Better approach would be to use a Map.
I have made use of ArrayList and Collections package instead of regular arrays as a different flavor if it interests you check it out.
import java.util.*;
public class OccurrencesCount {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
List<Integer> list = new ArrayList<>();
//Accepting input.
System.out.print("Enter 10 integers between 1 and 100: ");
for (int i = 0; i < 10; i++) {
list.add(scan.nextInt());
}
Collections.sort(list);
Integer prevNumber = null;
for (int number : list) {
if (prevNumber == null || prevNumber != number) {
int count = Collections.frequency(list, number);
System.out.println(number + " occurs " + count + (count > 1 ? " times." : " time."));
}
prevNumber = number;
}
}
}
I got it figured out guys, only changed a couple of small things inside the conditions and everything went smoothly! Thanks for the help! Now I just need to find a way to restrict the inputs from going above 100.
import java.util.*;
public class CountOccurrences
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int[] list = new int[10];
//Accepting input.
System.out.print("Enter 10 integers between 1 and 100: ");
for(int i = 0;i<=9;i++){
list[i] = scan.nextInt();
}
//Sort out the array.
Arrays.sort(list);
int count = 1;
for(int i = 1;i<=10;i++){
if(i<=9 && list[i-1]==list[i]){
count++;
}
else{
if(count<=1){
System.out.println(list[i-1] + " occurs 1 time.");
}
else{
System.out.println(list[i-1] + " occurrs " + count + " times.");
count = 1;
}
}
}
}
}
Building a program that can check if a random number is = to a specific number. Here is what I have so far. I am generating a random number 10 times. And I want it to print out "The number (int var) was found (How ever many times it generated) times.". I keep running into problems such as trying to pull static variable from non-static variable. I'm not sure how to check if the integer is = to the random number.
import java.util.Random;
public class Driver{
public static void main(String[] args)
{
Loop.loop4(4);
}
public class Loop
{
public static void loop4(int val)
{
for(int iteration = 1; iteration <=10; iteration ++)
{
Random number = new Random();
number.nextInt(10);
}
System.out.println("The number " + val +" was found " (Dont know how to do this part);
}
}
You should try something like:
int count = 0;
for(int iteration = 1; iteration <=10; iteration ++) {
Random number = new Random();
int n = number.nextInt(10);
if(n == val) count++;
}
System.out.println("The number " + val +" was found " + count + " number of times");
Just compare val with the random number generated and see if they are equal in the if() {...}, keep a counter to keep track of how many times the random number was equal to val.
#thegauravmahawar 's answer seems decent and interesting.
Nonetheless, here's a suggestion on how to enhance your code:
(Don't mind if it's got any minor errors; I wrote it all on nano)
package loop;
import java.util.Random;
public class Loop {
public static void main(String[] args){
int number = 100, range = 100 // Type in any ints
if looper(number, range) { System.out.println("Number %i found!", number) }
else { System.out.println("Number not found!" ) }
}
public bool looper(int numberToBeFound, int range){
guard numberToBeFound<=range else { System.out.println("number to be found is
greater than range!") }
for (int i = 1; i<=range; i++) {
Random randomNumber = new Random();
randomNumber.nextInt(range)
if randomNumber == NumberToBeFound { break; return true } // Unsure if this'll work
}
return false
}
}
The program is meant to count how many even numbers that have been inputted by the user. However, when the user inputs even numbers along with odd numbers the program crashes. But when the user enters all odd or even the program works fine. I can't seem to find the error either as the error message returns:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at AllEven.getEven(AllEven.java:52)
at AllEven.read(AllEven.java:41)
at AllEven.main(AllEven.java:10)
Java Result: 1
The code for the program is below and any help would be greatly appreciated
import java.util.Scanner;
public class AllEven
{
private static int evenCount;
private static int[] evenArray;
private static int count;
public static void main (String args [])
{
read();//LINE 10
}
public static int [] read ()
{
Scanner scanner = new Scanner (System.in);
System.out.println("Please enter the size of the array");
int arrayIn = scanner.nextInt();
if (arrayIn == 0)
{
System.out.println("No Array");
}
else
{
System.out.println("------------------");
}
int userArray [] = new int [arrayIn];
for (int i = 0; i < userArray.length; i++)
{
System.out.println("Please enter a value for position: " + i);
arrayIn = scanner.nextInt();
userArray[i] = arrayIn;
if (arrayIn % 2 == 0)
{
evenCount++;
}
}
getEven(userArray);//LINE 41
return userArray;
}
public static int [] getEven(int[] userArray)
{
if (evenCount > 0)
{
evenArray = new int [evenCount];
for (int i = 0; i < userArray.length; i++)
{
evenArray[count] = userArray[i]; //LINE 52
count++;
}
print (evenArray);
}
else
{
System.out.println("No even numbers found");
}
return evenArray;
}
public static void print (int [] evenArray)
{
System.out.println();
System.out.println("Even numbers in the array are: ");
for (int i = 0; i < evenArray.length; i++)
{
System.out.println(evenArray[i]);
}
}
}//endprogram
userArray.length is not always equal to evenCount
problematic code
evenArray = new int [evenCount];
for (int i = 0; i < userArray.length; i++)
{
evenArray[count] = userArray[i];
Your even count is less than the size of the user array, yet you are indexing into the even array count times. You are incrementing count each time you get an item from the input array, and the input array will always be larger than the even array if you enter both even and odd numbers.