'GuessingGame Math.random - Create a guessing game where the c [closed]
I am creating an Instantiable Class Guessing Game app where computer comes up with a random number and the user guesses (output winner or loser), however there is something not working on my code, it only returns me Winner if userInput = 0.
I have added a System.out.println as check the random number generated and confirm if the code was working properly.
Could you please help me?
Guessing Game Class Code
public class GuessingGame {
//define variable
private int randomNum;
private int userInput;
private String msg;
//Constructor method
public void GuessingGame(){
randomNum = 0;
userInput = 0 ;
msg = "";
}
//set method
public void setRandomNum(double randomNumber){
this.randomNum = randomNum;
}
public void setUserInput(int userInput){
this.userInput = userInput;
}
// compute method
public void computeMsg() {
if (randomNum == userInput) {
msg = "Winner";
} else {
msg = "Loser";
}
}
//get method
public String getMsg(){
return msg;
}
}
Guessing Game App Class Code
import javax.swing.*;
public class GuessingGameApp {
public static void main(String[] args) {
//declare variables
int randomNum = (int) (Math.random() * 20);
int userInput;
String msg;
//declare and create objects
GuessingGame c;
c = new GuessingGame();
System.out.println(randomNum);
userInput = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter a guess"));
//set
c.setRandomNum(randomNum);
c.setUserInput(userInput);
//compute
c.computeMsg();
//get
msg = c.getMsg();
//output
JOptionPane.showMessageDialog(null, msg);
}
}
Solution 1:[1]
Your problem is right here...
public void setRandomNum(double randomNumber) {
this.randomNum = randomNum;
}
You pass in randomNumber, but you assign randomNum to itself
It should be...
public void setRandomNum(double randomNumber) {
this.randomNum = randomNumber;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
