I know this question has been answered before, and I have looked here: math.random, only generating a 0? as well as a few other forums, but thus far have been unable to answer my question.
I am trying to produce a random number between 1 and 3 (this includes 1 & 3) for a Rock Paper Scissors game. Unfortunately, the output for my random number is always 0.
Please be aware that I am not allowed to use the Random(); class, and must use the Math.random method to achieve this. Here is my code for Random number:
public static int randomComputerChoice(int highVal, int lowVal) {
do{
highVal = 4;
lowVal = 0;
computerChoice=0;//resets random number
//generates and returns a random number within user's range
computerChoice = (int)((Math.random()* highVal)+1);
} while((computerChoice>= highVal)||(computerChoice<= lowVal));
return (computerChoice);
}
}
I wasn't sure if this was necessary, but I feel like the error could be in the rest of my code.
import java.util.Scanner;
import java.io.IOException;
public class RockPaperScissors {
static int weaponChoice;
static int computerChoice;
static int lowVal = 1;
static int highVal = 3;
/**
* @param args the command line arguments
* @throws java.io.IOException
*/
public static void main(String[] args) throws IOException {
Scanner userInput = new Scanner(System.in);
System.out.println(" =========================");
System.out.println("====ROCK=PAPER=SCISSORS====");
System.out.println(" =========================");
int playAgain = 1; //sets a play again function
do {
System.out.println("Please select your weapon.");
System.out.println("1 - Rock");
System.out.println("2 - Paper");
System.out.println("3 - Scissors");
System.out.println("Choose wisely:");
String choice = userInput.nextLine();
weaponChoice = Integer.parseInt(choice);
do {
if (weaponChoice != 1 && weaponChoice != 2 && weaponChoice != 3) {
System.out.println("Please choose again, grasshopper. There are only"
+ " three choices.");
System.out.println("1 - Rock");
System.out.println("2 - Paper");
System.out.println("3 - Scissors");
choice = userInput.nextLine();
weaponChoice = Integer.parseInt(choice);
}
} while (weaponChoice != 1 && weaponChoice !=2 && weaponChoice != 3);
if (weaponChoice == 1) {
System.out.println("You have selected Rock as your weapon.");
}
else if (weaponChoice == 2) {
System.out.println("You have selected Paper as your weapon.");
}
else {
System.out.println("You have selected Scissors as your weapon.");
}
//Computer's Choice
System.out.println("The computer's choice is "+computerChoice);
} while (playAgain == 1);
}
public static int randomComputerChoice(int highVal, int lowVal) {
do{
highVal = 4;
lowVal = 0;
computerChoice=0;//resets random number
//generates and returns a random number within user's range
computerChoice = (int)((Math.random()* highVal)+1);
} while((computerChoice>= highVal)||(computerChoice<= lowVal));
return (computerChoice);
}
}
Thanks for any help! It is greatly appreciated.