I am making a lottery application in Java. My problem is that I think everything is in place and it (the IDE) is telling me that "int lotteryNumbersCount = Eck_LotteryClass.getLotteryNumbers().length;" needs to be static. So I change it to a static int and then I have to change it again in my class. Problem is when I finally run it I get all 0's for my random lottery data. Please help me find the errors in my ways. Total newb here and I've been looking online here but I want to try to figure it out without just copying code somewhere.
Eck_LotteryClass
import java.util.Random;
public class Eck_LotteryClass {
//instance field
private int lotteryNumbers [];
//Create random lottery numbers method array
public int [] getRandomNumbers(){
lotteryNumbers = new int [5];
Random r = new Random();
for(int i = 0; i < 5; i++)
lotteryNumbers[i] = r.nextInt(10);
return lotteryNumbers;
}
public int compareNumbers(int[] usersNumbers) {
int matchedNums = 0;
if (usersNumbers.length == lotteryNumbers.length) {
for (int i = 0; i < lotteryNumbers.length; i++) {
if (usersNumbers[i] == lotteryNumbers[i]) {
matchedNums ++;
}
}
}
return matchedNums;}
// Display the random lottery numbers for the user
public int [] getLotteryNumbers() {
return lotteryNumbers;
}
}
Eck_LotteryTester
import java.util.Scanner;
import java.util.Arrays;
public class Eck_LotteryTester{
public static void main(String[] args) {
Eck_LotteryClass lottery = new Eck_LotteryClass();
int lotteryNumbersCount = Eck_LotteryClass.getLotteryNumbers().length;
System.out.println("The Pennsylvania Lottery\n");
System.out.println("There are " + lotteryNumbersCount
+ " numbers in my lottery, they are 0 through 9. "
+ "See if you can win big CASH prizes!!!\n");
// Asks the user to enter five numbers.
Scanner keyboard = new Scanner(System.in);
int numbers[] = new int[lotteryNumbersCount];
for (int index = 0; index < numbers.length; index++) {
System.out.print(String.format("Enter Number %d: ", index + 1));
numbers[index] = keyboard.nextInt();
}
// Display the number of digits that match the randomly generated
// lottery numbers.
int match = lottery.compareNumbers(numbers);
if (match == lotteryNumbersCount) {
// If all of the digits match, display a message proclaiming the
// user a grand prize winner.
System.out.println("\nYOU WIN, GO SEE D. LEETE FOR YOUR GRAND PRIZE!!!");
} else {
System.out.println("\nThe winning numbers are " + Arrays.toString(Eck_LotteryClass.getLotteryNumbers()) +
"\nYou matched " + match + " number(s).");
}
}
}
Change
int lotteryNumbersCount = Eck_LotteryClass.getLotteryNumbers().length;
to
int lotteryNumbersCount = lottery .getLotteryNumbers().length;
and you won't have to change the methods signature to static. Also you'll be talking about the same variable.
Also change
// Display the random lottery numbers for the user
public int [] getLotteryNumbers() {
return lotteryNumbers;
}
to
// Display the random lottery numbers for the user
public int [] getLotteryNumbers() {
return getRandomNumbers();
}
So the array gets initialized. And changing the signature of
public int [] getRandomNumbers
to
private int [] getRandomNumbers
wouldn't hurt
package New_list;
import java.util.Scanner;
import java.util.Random;
public class Lottery {
private static Scanner scan;
public static void main(String[] args) {
System.out.println("\t\t\tWelcome to Harsh Lottery System.\n");
Random random = new Random();
int lottery_win_1 = random.nextInt(10);
// Print Lottery winning number...1 :P
// System.out.println(lottery_win_1 + "\n");
int lottery_win_2 = random.nextInt(10);
// Print Lottery winning number...2 :P
// System.out.println(lottery_win_2 + "\n");
boolean loop = true;
while(loop){
System.out.println("\t\t\tEnter your 2 Digit Lottery number.\n");
scan = new Scanner(System.in);
int lottery_no = scan.nextInt();
if ((lottery_no >= 0) && (lottery_no <= 99)) {
int lottery_no_1, lottery_no_2;
if (lottery_no > 9) {
lottery_no_1 = lottery_no / 10;
lottery_no_2 = lottery_no % 10;
} else {
lottery_no_1 = 0;
lottery_no_2 = lottery_no;
}
if ((lottery_win_1 == lottery_no_1)
&& (lottery_win_2 == lottery_no_2)) {
System.out
.println("\t\t\tCongratulation you win lottery,and you win $10000.\n");
} else if ((lottery_win_1 == lottery_no_2)
&& (lottery_win_2 == lottery_no_1)) {
System.out
.println("\t\t\tCongratulation your inverse no is lottery winer number so that you win $4000.\n");
} else if ((lottery_win_1 == lottery_no_1)
|| (lottery_win_1 == lottery_no_2)
|| (lottery_win_2 == lottery_no_1)
|| (lottery_win_2 == lottery_no_2)) {
System.out
.println("\t\t\tCongratulation your one digit from your lotter number match to the lottery winner.so you win $1000.\n");
} else {
System.out.println("\t\t\tSorry,Please try again\n");
System.out.println("\t\t\tDo you want to try again\n\t\t\tPress 1 for Continue\n\t\t\tPress 2 for exit\n");
int ch = scan.nextInt();
switch(ch){
case 1: System.out.println("\t\t\tOk...Try again\n");
break;
case 2: System.out.println("\t\t\tBbye... See you later\n");
loop = false;
break;
}
}
} else {
System.out.println("\t\t\tSorry,Please choose 2 digit number\n");
}
}
}
}
Related
I am relatively new to java programming. I am currently working on building a mini guessing game, as a project to learn more Java. I am having some issues with the following:
Here are the 4 main things I am having trouble solving.
Record the answer for each user, if incorrect.
If the user was correct, skip them in subsequent rounds.
Once all players have guessed their correct number, print out the number of guesses it took for each one to guess correctly, the incorrect responses, and show a ranking of the players.
Ask if the user(s) wish to play again. If so, reset all values.
Here are the methods that I have written;
import java.io.*;
public class MultiPlayerRandomGame {
// this method asks how many users will be playing and returns the number of users
public static int howManyUsers() {
System.out.println("How many users will be playing?");
int players = IO.readInt();
return players;
}
// this method generates and returns a random number
public static int generateRandomNumber() {
int randomNumber = (int) (Math.random() * 100);
return randomNumber;
}
// this method compares user's entered guess and the generated random number then returns true/false
public static boolean compareGuess(int guess, int randomNumbers) {
boolean isGuessCorrect = false;
if (guess == randomNumbers) {
System.out.println("CORRECT!");
isGuessCorrect = true;
} else if (guess > randomNumbers) {
System.out.println("Too High");
} else if (guess < randomNumbers) {
System.out.println("Too Low");
}
System.out.println("test1");
return isGuessCorrect;
}
// this method determines whether Player N is correct or incorrect
public static boolean nextPlayer(int numOfUsers, int[] numberOfGuesses, int[] randomNumbers, int[][] numberBoard) {
for (int n = 0; n < numOfUsers; n++) {
int guessedNumber = numberOfGuesses[n];
/* if (guessedNumber == 0) {
return false;
}*/
if (numberBoard[n][guessedNumber] != randomNumbers[n]) {
return false;
}
}
return true;
}
/* this method is supposed to print out the number of guesses it took each player to guess their correct number
* CORRECTION: change the logic of this method to printing the number of guesses for one player then
* in the main method or wherever, make a for loop that prints out the number of guesses for each player
*/
public static void amountOfGuesses(int numOfUsers, int [] numberOfGuesses, int [][] numberBoard) {
int n = 0;
for ( int i = 0; i < numOfUsers; i++ ) {
n = n + 1;
System.out.println("Player " + n + " guessed " + numberOfGuesses[i]+ " time(s)");
}
}
// this method determines whether the user(s) would like to play again
public static boolean playAgain(String answer) {
boolean userWillPlayAgain;
if (answer.compareToIgnoreCase("no") == 0) {
userWillPlayAgain = false;
}
else {
userWillPlayAgain = true;
}
return userWillPlayAgain;
}
// this method controls the entire game
public static boolean playGame(){
boolean gameTerminate = false;
int numOfUsers = howManyUsers();
int [] randomNumbers = new int[numOfUsers];
int [] numberOfGuesses = new int [numOfUsers];
int [][] numberBoard = new int [numOfUsers][100];
// this for loop assigns the n random number(s) to the n player(s)
for (int n = 0; n < numOfUsers; n++){
randomNumbers[n] = generateRandomNumber();
System.out.println("PLAYER " + (n+1) + "'s RANDOM NUMBER: " + randomNumbers[n]);
}
do {
for (int i = 0; i < numOfUsers; i++) {
int guessedNumber = numberOfGuesses[i];
if (guessedNumber == 0 || numberBoard[i][guessedNumber-1] != randomNumbers[i]) {
System.out.println("Enter your guess Player " + (i+1) + ":");
int enteredGuess = IO.readInt();
numberBoard[i][guessedNumber] = enteredGuess;
numberOfGuesses[i] = guessedNumber + 1;
if(compareGuess(enteredGuess, randomNumbers[i])){
return true;
}
}
}
/* int n = 0;
* for ( int j = 0; j < numOfUsers; j++ ) {
n = n + 1;
System.out.println("Player " + n + " guessed " + numberOfGuesses[j]+ " time(s)"); }
*/
} while (nextPlayer(numOfUsers, numberOfGuesses, randomNumbers, numberBoard) == false);
// System.out.println("test");
return gameTerminate;
}
public static void main(String[] args){
boolean playing = true;
while (playing) {
playGame();
System.out.println("Would you like to play again?");
String answer = IO.readString();
playing = playAgain(answer);
}
System.out.println("OK, goodbye!");
}
}
Main issue as of right now: The game terminates and asks if user would like to play again after a player guesses their number, rather than after every player guesses their number.
Do I need actual Objects to make this happen and track every player or can this still be solved without objects? This is a territory I am unfamiliar with.
Right now your playGame method returns true back to main whenever any guess returns correct from compareGuess.
I would recommend setting up another array boolean[] correctGuess in playGame and mark the player number index as true if a player guesses correctly. You can use this new array to skip players who have guessed correctly, also. Once all players are marked true you can return to main.
This won't help improve your current code, but the same game can easily implemented using objects. In my opinion, the code is cleaner and easier to read.
Objects allow you to encapsulate the data required by each class. The target, number of guesses, and whether they were correct is stored in the Person object instead of in a multi-dimensional array. The values can be accessed by referencing the Person object - e.g. person.numGuesses or person.target.
By using objects, you can keep specific functionality scoped out of the main class. i.e. abstract away the implementation. In a future version of the game, you may want to change the way the target value is incremented; by using objects, the change can be made in the class which sets and checks the value - without affecting any other classes.
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
public class Game {
private final List<Person> personList = new ArrayList<>();
private Game(int numPlayers) {
for (int i = 0; i < numPlayers; i++) {
personList.add(new Person(i)); // Fill the player list
}
}
public static void main(String[] args) {
System.out.print("Enter the number of players: ");
Scanner sc = new Scanner(System.in);
int numPlayers = sc.nextInt();
// Initialise with the number of players
Game g = new Game(numPlayers);
g.mainLoop(); // Play the game
boolean playAgain = false;
do {
System.out.print("Do you wish to play again?: ");
String in = sc.next();
playAgain = "yes".equals(in);
if (playAgain) {
g.resetAll();
g.mainLoop();
}
} while (playAgain); // Only loop if they answered "yes"
}
private boolean allCorrect() {
// Check if all players have answered correctly
return personList.stream().allMatch(p -> p.correct);
}
private void resetAll() {
for (Person p : personList) {
p.reset(); // Reset each person
}
}
private void mainLoop() {
while (!allCorrect()) {
for (Person p : personList) {
p.doGuess(); // Ask for the guess
}
}
// Everyone is correct, print the scores.
for (Person p : personList) {
System.out.println("Player " + p.id + " => " + p.numGuesses + " guesses");
}
}
}
class Person {
final int id;
int numGuesses;
boolean correct;
private int target;
Person(int id) {
this.id = id;
target = new Random().nextInt(100); // Each player has a random target between 0-100
}
void doGuess() {
if (correct) {
// Skip turn if they're already correct
return;
}
numGuesses++;
System.out.print("Player " + id + " guess " + numGuesses + "(" + target + "): ");
Scanner sc = new Scanner(System.in);
int i = sc.nextInt(); // Read the guess
if (i == target) {
correct = true;
System.out.println("Correct!");
}
}
void reset() {
target = new Random().nextInt(100); // New target between 0-100
numGuesses = 0; // Reset the counter
correct = false;
}
}
So I have this assignment for class about doing something that implemented methods. I made this really simple program to give you a lucky number of the day. But for some reason, I couldn't get it to run properly more than twice.
The version I'm posting doesn't contain the loop, but I tried about 10 different ways and it just wouldn't work. Either it would keep spitting out numbers endlessly, or it would print out the welcome lines again instead of just the "would you like another number y/n" line. If someone could just help me figured out how I should have organized it so that the loop only displays this line:
Would you like to receive another number? y/n
and then if the user decides yes, the intro method runs again and that line displays again until uses presses "n"
here's the code:
import java.util.Scanner;
import java.math.BigInteger;
import java.util.Random;
public class MinOppgave2 {
public static void main(String[] args) {
menu();
}
public static void menu(){
//intro text
System.out.println("Welcome to lucky number of the day!");
System.out.println("What kind of number would you like today?");
intro();
Scanner input = new Scanner(System.in);
System.out.println("Would you like to receive another number? y/n");
String txtinput = input.nextLine();
if (txtinput.equalsIgnoreCase("y")){
intro();
}
else if (txtinput.equalsIgnoreCase("n")){
System.out.println("That's all for now, have a nice day!");
}
System.out.println("That's all for now, have a nice day!");
}
public static void intro(){
// user choice
Scanner input = new Scanner(System.in);
System.out.println("Please choose between: even odd or prime");
String text1 = input.nextLine();
//if/else user choice arguments
if (text1.equalsIgnoreCase("even"))
Evennum();
else if (text1.equalsIgnoreCase("odd"))
Oddnum();
else if (text1.equalsIgnoreCase("prime"))
Prime();
else
menu();
}
public static void Evennum(){
// random number generator
int num = 0;
Random rand = new Random();
num = rand.nextInt(1000) + 1;
while (!isEven(num)) {
num = rand.nextInt(1000) + 1;
}
System.out.println(num);
}
public static void Oddnum(){
// random number generator
int num = 0;
Random rand = new Random();
num = rand.nextInt(1000) + 1;
while (!isOdd(num)) {
num = rand.nextInt(1000) + 1;
}
System.out.println(num);
}
public static void Prime(){
// random number generator
int num = 0;
Random rand = new Random();
num = rand.nextInt(1000) + 1;
while (!isPrime(num)) {
num = rand.nextInt(1000) + 1;
}
System.out.println(num);
}
// prime checker
private static boolean isPrime(int numin){
if (numin <= 3 || numin % 2 == 0)
return numin == 2 || numin == 3;
int divisor = 3;
while ((divisor <= Math.sqrt(numin)) && (numin % divisor != 0))
divisor += 2;
//true/false prime answer
return numin % divisor != 0;
}
private static boolean isEven(int numin){
//math argument for even number
return (numin % 2) == 0;
}
private static boolean isOdd(int numin){
//math argument for even number
return (numin % 2) == 1;
}
}
Wrong recursion on the wrong place...
Try this:
public static void intro() {
System.out.println("Welcome to lucky number of the day!");
System.out.println("What kind of number would you like today?");
}
public static String takeInput() {
Scanner input = new Scanner(System.in);
return input.nextLine();
}
public static boolean pickNumber() {
System.out.println("Would you like to receive another number? y/n");
if (!takeInput().equalsIgnoreCase("y")) {
System.out.println("That's all for now, have a nice day!");
return false;
}
System.out.println("Please choose between: even odd or prime");
String chosen = takeInput();
//if/else user choice arguments
if (chosen.equalsIgnoreCase("even"))
Evennum();
else
if (chosen.equalsIgnoreCase("odd"))
Oddnum();
else
if (chosen.equalsIgnoreCase("prime"))
Prime();
return true;
}
public static void main(String[] args) {
intro();
while (pickNumber())
;
}
Though the problem seemed simple, here it is :-
A Kaprekar number is a positive whole number n with d digits, such that when we split its square into two pieces - a right hand piece r with d digits and a left hand piece l that contains the remaining d or d−1 digits, the sum of the pieces is equal to the original number (i.e. l + r = n).
The Task
You are given the two positive integers p and q, where p is lower than q. Write a program to determine how many Kaprekar numbers are there in the range between p and q (both inclusive) and display them all.
Input Format
There will be two lines of input: p, lowest value q, highest value
Constraints:
0<p<q<100000
Output Format
Output each Kaprekar number in the given range, space-separated on a single line. If no Kaprekar numbers exist in the given range, print INVALID RANGE.
I could not clear the test cases in the range
22223
99999
In the above range the follwoing numbers should have been generated :-
77778 82656 95121 99999
Here is my code :-
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner scan = new Scanner(System.in);
int p = scan.nextInt();
int q = scan.nextInt();
boolean exist = false;
if(q <= p){
System.out.println("INVALID RANGE");
}
int m = 0,n = 0;
long sqr = 0;
String numb = "";
String[] digits = new String[2];
for(int i = p; i <= q; i++){
if(i == 1)System.out.print(1 + " ");
else{
sqr = i*i;
numb = String.valueOf(sqr);// Changing it into a string.
if(numb.length() % 2 == 0){
digits[0] = numb.substring(0, numb.length()/2);//Splitting it into two parts
digits[1] = numb.substring(numb.length()/2);
}else{
digits[0] = numb.substring(0, (numb.length() - 1)/2);
digits[1] = numb.substring((numb.length() -1)/2);
}
if(digits[0] == "" )
m = 0;
if(digits[1] == "")
n = 0;
if(!digits[1].equals("") && !digits[0].equals("")){
m = Integer.parseInt(digits[0]);
n = Integer.parseInt(digits[1]);
}
if(i == (m + n) ){ //Testing for equality
System.out.print(i + " ");
exist = true;
}
}
}
if(exist == false){// If exist is never modified print Invalid Range.
System.out.println("INVALID RANGE");
}
}
}
import java.util.*;
public class Kaprekar
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number");
int num=sc.nextInt();
int sq=num*num; String sq1=Integer.toString(sq);
int mid=(Integer.toString(sq).length())/2;
int rem=sq%((int)Math.pow(10,sq1.length()-mid));
int quo=sq/((int)Math.pow(10,sq1.length()-mid));
int sum=rem+quo;
if(sum==num)
{System.out.println("Kaprekar");}else{System.out.println("Not Kaprecar");}
}
}
Changing the type of Loop index i from int to long fixed the problem.
The square computation of i*i was overflowing the upper limit of int so by changing it to long we were able to get the required computation done.
Thanks to Rup for pointing this out.
The code which cleared all the test cases is here :-
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner scan = new Scanner(System.in);
int p = scan.nextInt();
int q = scan.nextInt();
boolean exist = false;
if(q <= p){
System.out.println("INVALID RANGE");
return;
}
int m = 0,n = 0;
long sqr = 0;
String numb = "";
String[] digits = new String[2];
for(long i = p; i <= q; i++){
if(i == 1)System.out.print(1 + " ");
else{
sqr = i*i;
numb = String.valueOf(sqr);
if(numb.length() % 2 == 0){
digits[0] = numb.substring(0, numb.length()/2);
digits[1] = numb.substring(numb.length()/2);
}else{
digits[0] = numb.substring(0, (numb.length() - 1)/2);
digits[1] = numb.substring((numb.length() -1)/2);
}
if(digits[0] == "" )
m = 0;
if(digits[1] == "")
n = 0;
if(!digits[1].equals("") && !digits[0].equals("")){
m = Integer.parseInt(digits[0]);
n = Integer.parseInt(digits[1]);
}
if(i == (m + n) ){
System.out.print(i + " ");
exist = true;
}
}
}
if(exist == false){
System.out.println("INVALID RANGE");
}
}
}
import java.io.*;
import java.math.*;
import java.util.*;
class Kaprekar {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int p = scanner.nextInt();
int q = scanner.nextInt();
long i,n,s,a,c,k,d,e=0;
for(i=p;i<=q;i++)
{
k=i;d=0;
while(k!=0)
{
d++;
k=k/10;
}
c=0;s=0;n=i*i;
while(n!=0)
{
a=n%10;
n=n/10;
s=s+ (int)Math.pow(10,c)*a;
c++;
if(n+s==i&&(c==d||c==d-1)&&s!=0)
{
System.out.print(i+" ");
e++; break;
}
}
}
if(e==0)
{
System.out.println("INVALID RANGE");
}
scanner.close();
}
}
import java.util.Random;
import java.util.Scanner;
import javax.swing.JOptionPane;
import java.util.*;
public class GuessingGameGUI {
public static void main(String[] args) {
Random rand = new Random();
int value = rand.nextInt(32) + 1;
int guesses = 0, LowGuess = 0, HighGuess = 0; //ADDED LowGuess AND HighGuess
Scanner input = new Scanner(System.in);
int guess;
boolean win = false;
while (win == false) {
JOptionPane.showInputDialog("Guess a number between 1 and 32: ");
guess = input.nextInt();
guesses++;
if (guess == value) {
win = true;
} else if (guess < value) {
JOptionPane.showInputDialog("Your guess is lower than random number");
LowGuess++; //COUNTER TO KEEP TRACK OF LOW GUESSES
} else if (guess > value) {
JOptionPane.showInputDialog("Your guess is higher than random number");
HighGuess++; //COUNTER TO KEEP TRACK OF HIGH GUESSES
}
}
JOptionPane.showMessageDialog(null, "You win! You are the worst guesser in history!");
JOptionPane.showMessageDialog(null, "The number was: " + value);
// ADDED FROM HERE (GUESSES)
JOptionPane.showMessageDialog(null, "Number of Guesses:" + guesses);
for (int x = 1; x <= guesses; x++) {
for (int a = 1; a <= guesses; a++) {
if (a == guesses) {
JOptionPane.showMessageDialog(null, "*");
}
}
} // TO HERE FOR AMOUNT OF GUESSES
// I ADDED FROM HERE (LOW)
JOptionPane.showMessageDialog(null, "Smaller Guesses:" + LowGuess);
for (int Low_i = 1; Low_i <= LowGuess; Low_i++) {
for (int Low_e = 1; Low_e <= LowGuess; Low_e++) {
if (Low_e == LowGuess) {
JOptionPane.showMessageDialog(null, "*");
}
}
} // Then TO HERE FOR LOW
// I ADDED FROM HERE (HIGH)
JOptionPane.showMessageDialog(null, "Largest Guesses:" + HighGuess);
for (int High_i = 1; High_i <= HighGuess; High_i++) {
for (int High_e = 1; High_e <= HighGuess; High_e++) {
if (High_e == HighGuess) {
JOptionPane.showMessageDialog(null, "*");
}
}
} //FINALLY TO HERE FOR HIGH
}
}
// when I run my program the message box pops up when i enter my guessing number, however it seems to stop and nothing else pops up to let me know if i guessed to high or to low.
Take these lines, for example:
JOptionPane.showInputDialog("Guess a number between 1 and 32: ");
guess = input.nextInt();
A prompt displays that asks you to "Guess a number between 1 and 32". So you enter the number, and then execution stops because your Scanner is awaiting your input. You need to completely remove your Scanner so you won't have these frequent interruptions.
The showInputDialog method of JOptionPane returns a String, as shown in the example from the Javadocs:
Show a dialog asking the user to type in a String:
String inputValue = JOptionPane.showInputDialog("Please input a value");
As is, you're throwing away the value returned from the method when you should instead be assigning it to your variables. In order to assign the returned value to your int variable guess, use Integer.parseInt:
guess = Integer.parseInt(JOptionPane.showInputDialog("Guess a number between 1 and 32: "));
JOptionPane.showInputDialog returns String than you have to convert that String to int using Parse methods, every time you receive input.
String input = JOptionPane.showInputDialog();
Int number = Integer.parseInt(input);
I'm new to Java and I have a program players guess the price of an item (exact price is inputted first). I have an array called winnerCount which keeps track of the rounds won by each player. I want to output this using "JOptionPane.showMessageDialog" and part of the code involves giving each player a prize based on the rounds won. So for my pseudocode I have IF roundsWon = 1 THEN prize won: $15,125. When I try the same idea in Java it gives me the error "incomparable types" since its comparing int and int[]. Since Java can't compare different data types, what way(s) can I output the desired result ("winnerCount" and prizes won by each player)?
Here's what I'm working with
import javax.swing.JOptionPane;
import java.lang.Math;
import java.util.*;
public class priceIsRight {
public static void main(String[] args) {
double [] numPlayers = new double [4];
double exactPrice = getExactPrices();
double [] guessPrice = getGuessPrices(exactPrice);
int roundsWon = getRoundsWon(guessPrice, exactPrice);
int numRounds = 0;
int [] winnersCount = new int [4];
int roundWinner = getRoundsWon(guessPrice, exactPrice);
int prizesWon = calculatePrizesWon(winnersCount, roundWinner);
}
public static int getRoundsWon(double[] guessPrice, double exactPrice) {
int roundWinner = getRoundsWon(guessPrice, exactPrice);
int [] winnersCount = new int [4];
int numRounds = 0;
do {
double minValue = Math.abs(exactPrice-guessPrice[0]);
roundWinner = 0;
for (int i=1;i < guessPrice.length; i++) {
double diff = Math.abs(exactPrice-guessPrice[i]);
if (diff<minValue) {
minValue=diff;
roundWinner=i;
}
winnersCount[roundWinner]++;
}
}
while (numRounds <=3);
return roundWinner;
}
//Outputs result
public static int calculatePrizesWon(int [] winnersCount, int roundWinner) {
int prizesWon = 0;
if (winnersCount = 0) {
JOptionPane.ShowMessageDialog(null, "Prize won: $106 consolidation prize!");
}
else if (winnersCount = 1) {
JOptionPane.ShowMessageDialog(null, "Prize won: $15,125!");
}
else if (winnersCount = 2) {
JOptionPane.ShowMessageDialog(null, "Prize won: $30,110!");
}
else if (winnersCount = 3) {
JOptionPane.ShowMessageDialog(null, "Prize won: $15,120,000!");
}
}
}
You need to specify which location in the array you want to compare. Try this:
public static int calculatePrizesWon(int[] winnersCount, int roundWinner) {
int prizesWon = 0;
if (winnersCount[roundWinner] == 0) {
JOptionPane.showMessageDialog(null, "Prize won: $106 consolidation prize!");
} else if (winnersCount[roundWinner] == 1) {
JOptionPane.showMessageDialog(null, "Prize won: $15,125!");
} else if (winnersCount[roundWinner] == 2) {
JOptionPane.showMessageDialog(null, "Prize won: $30,110!");
} else if (winnersCount[roundWinner] == 3) {
JOptionPane.showMessageDialog(null, "Prize won: $15,120,000!");
}
return prizesWon; // Replace this with the real prize won number.
}
You'll probably do better using a switch statement instead. If you want to see or receive comments on other things you can do better post a comment.
There are some things that don't make sense about this code. For example, why did you make numPlayers a double[]? Wouldn't it make more sense for it to be
int numPlayers = 4;
And for your winnersCount, is that storing how many rounds each player won? If so then I assume your calculatePrizesWon method should be iterating through each player, and outputting their prize.
Something like
public static int calculatePrizesWon(int [] winnersCount, int roundWinner)
{
int prizesWon = 0;
for (int i = 0; i < winnersCount.length; i++)
{
if (winnersCount[i] == 0)
{
JOptionPane.ShowMessageDialog(null, "Player "+i+" - Prize won: $106 consolidation prize!");
}
else if (winnersCount[i] == 1)
{
JOptionPane.ShowMessageDialog(null, "Player "+i+" - Prize won: $15,125!");
}
else if (winnersCount[i] == 2)
{
JOptionPane.ShowMessageDialog(null, "Player "+i+" - Prize won: $30,110!");
}
else if (winnersCount[i] == 3)
{
JOptionPane.ShowMessageDialog(null, "Player "+i+" - Prize won: $15,120,000!");
}
}
}
Also, what is the "round winner" parameter you're passing into calculatePrizesWon for?
And what is the "prizesWon" variable for? If, for example, a player won three rounds, then wouldn't they also have won three prizes? So what distinction is there between the winnersCount and the prizesWon?
I'll try to help but you'll need to explain what you're doing a little more clearly.