Reputation: 11
I have a program where i'm required to seperate as much out as possible as different methods and classes.
I have a rng, thats a class. I want to use the output from the rng in another class to compare it against a user selection to decide if they win or lose.
This is my rng.
package stockGame;
import javax.swing.JOptionPane; // Import this just in case I need a popup window
import java.util.Random; // Import this so i can use the random number
//The purpose of this class is to generate a random number between 1 and 12
public class Dice {
public static void Dice(){
Random random = new Random ();
JOptionPane.showMessageDialog(null,"The Computer picked " + (random.nextInt(12)+1));
}
}
Here is my if loop in the second class. I want to be able to say. If (option ==1 AND RNG is GREATER/LESS/EQUAL to 6){ That way it can compare and decide if the user has won or lost.
if (option ==1){
output = "You chose to trade less than £6 and the computer rolled RNG, so you win/lose,";
JOptionPane.showMessageDialog(null, output, "The Message", JOptionPane.INFORMATION_MESSAGE);
}
if (option ==2){
output = "You chose to trade more than £6";
JOptionPane.showMessageDialog(null, output, "The Message", JOptionPane.INFORMATION_MESSAGE);
}
if (option==3){
output = "You chose to trade exactly £6";
JOptionPane.showMessageDialog(null, output, "The Message", JOptionPane.INFORMATION_MESSAGE);
}
Hoping to get the ouput generated from RNG class to be used in another class
Upvotes: 1
Views: 44
Reputation: 6703
First of all, in order to return something from a method, that method signature must be set to return something different from void, in your case int
:
public class Dice {
public static int dice() {
Random random = new Random ();
int picked = random.nextInt(12)+1;
return picked;
}
}
and then use it:
int picked = Dice.dice();
JOptionPane.showMessageDialog(null,"The Computer picked " + picked);
if (option == 1 && picked < 6) {
output = "You chose to trade less than £6 and the computer rolled RNG, so you win/lose,";
}
if (option == 2 && picked > 6) {
output = "You chose to trade more than £6";
}
if (option == 3 && picked == 6) {
output = "You chose to trade exactly £6";
}
JOptionPane.showMessageDialog(null, output, "The Message", JOptionPane.INFORMATION_MESSAGE);
As you can see, I moved the message outside of the dice method because it's better to let do only a single task for each method, and by doing so you'll can reuse the dice method for other purposes without the need to show the message.
Upvotes: 1
Reputation: 13
You have to return the value from the Dice Method:
public class Dice {
public static int Dice(){
Random random = new Random ();
int randomNum = random.nextInt(12)+1;
JOptionPane.showMessageDialog(null,"The Computer picked " + randomNum);
return randomNum;
}
}
The if-statement should be something like this:
if(option == 1 && Dice.Dice() == 6)
{
//do something
}
Upvotes: 1