To summarise I am required to make a game, that a user has to guess the secret number. The secret number is generated by a random number.
Anyway I'm having a problem passing the random number to another class. Currently I am only passing it to the main class for testing purposes.
With this code the random number passes a zero
import java.util.Scanner; import java.util.Random; public class GameOptions { Scanner scan = new Scanner(System.in); public int SecretNumber; public int RandomNumber; public void ShowSecretNumber() { do { System.out.println("Enter a secret number between 1 and 10"); SecretNumber = scan.nextInt(); } while (SecretNumber < 1 || SecretNumber > 10); } public void SetRandomNumber (int RandomNumber) { Random number = new Random(); RandomNumber = number.nextInt(10) + 1; } public int getRandomNumber() { return RandomNumber; } }
And with this it passes whatever the value I set it to. Currently a 5.
import java.util.Scanner; import java.util.Random; public class GameOptions { Scanner scan = new Scanner(System.in); public int SecretNumber; public int RandomNumber; public void ShowSecretNumber() { do { System.out.println("Enter a secret number between 1 and 10"); SecretNumber = scan.nextInt(); } while (SecretNumber < 1 || SecretNumber > 10); } public void SetRandomNumber (int RandomNumber) { Random number = new Random(); RandomNumber = number.nextInt(10) + 1; } public int getRandomNumber() { return RandomNumber=5; } }
I can understand that RandomNumber=5 sets the value to 5 but why is this ignoring what the "SetRandomNumber" method sets the value to.
Any ideas??
Thanks in advanced
EDIT: Just adding the main class in case someone needs to see the output..
import java.util.Scanner; public class GameInterface { Scanner scan = new Scanner(System.in); public int lives; public static void main(String[] args) { //******// GameOptions number = new GameOptions(); //******// int mode = 0; int choice; int lives; int secretnumber; Scanner scan = new Scanner(System.in); Statistics statistics = new Statistics(); GameOptions secretNumber = new GameOptions(); NumberGuessingGame game = new NumberGuessingGame(); do { System.out.println("Select the mode of play: 1 Normal; 2 Testing"); mode = scan.nextInt(); } while (mode != 1 && mode != 2); do { System.out.println("*****MAIN MENU*****"); System.out.println("1. Start a new game"); System.out.println("2. Show the Stats"); System.out.println("3. Exit"); choice = scan.nextInt(); } while (choice != 1 && choice != 2 && choice != 3); switch (choice) { case 1: System.out.println("Enter number of lives"); lives = scan.nextInt(); System.out.println("Random Number = " + number.getRandomNumber()); if (mode == 2) { secretNumber.ShowSecretNumber(); } game.Play(); break; case 2: statistics.ShowStatistics(); break; case 3: System.exit(0); break; default: System.out.println("Choose Again"); } } }