excess the limit of random numbers in java? - java

I am actually working on a jackpot game where it generates random numbers and asks user to guess the random number, if it meets the criteria it prints win and if not it moves to other conditional statements.
I have almost finished writing my code and just I got confused on this step. My query is:
I have set a limit a on randInt(max) i.e random numbers but I want to know that if it exceeds its limit, it must show a message which I can't help myself out.
Please share your ideas if anyone can.
public class Jackpot {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
int mode;
System.out.println("Choose the difficulty level mode");
System.out.println("1: Easy (0-15)");
System.out.println("2: Medium (0-30)");
System.out.println("3: Difficult (0-50)");
System.out.println("or type another number to quit");
mode = input.nextInt();
if(mode == 1){
Start_Game(randInt(15));
}else if(mode == 2){
Start_Game(randInt(30));
}else if(mode == 3){
Start_Game(randInt(50));
}else if(mode <= 4 || mode >= 0){
System.out.println("Quit");
Restart_Game();
}
}
public static int randInt(int max){
int randomNum = (int) (Math.random() * ((max) + 1));
return randomNum;
}
public static int Start_Game(int max){
System.out.println("Please enter your guessed number");
int GuessNum , life = 5;;
do{
GuessNum = input.nextInt();
if(GuessNum == max){
System.out.println("You WIN");
break;
}else if(GuessNum > max){
System.out.println("BIG");
life--;
System.out.println("life: " + life);
}else if(GuessNum < max){
System.out.println("SMALL");
life--;
System.out.println("life: " + life);
}
}while(life != 0);
Restart_Game();
return 0;
}
public static void Restart_Game(){
System.out.println("if you want to restart the game \nPress Y to continue or N to exit");
char restart = input.next().charAt(0);
if(restart == 'Y' || restart == 'y'){
//Start_Game(randInt(10));
int mode;
System.out.println("Choose the difficulty level mode");
System.out.println("1: Easy (0-15)");
System.out.println("2: Medium (0-30)");
System.out.println("3: Difficult (0-50)");
System.out.println("or type another number to quit");
mode = input.nextInt();
if(mode == 1){
Start_Game(randInt(15));
}else if(mode == 2){
Start_Game(randInt(30));
}else if(mode == 3){
Start_Game(randInt(50));
}else if(mode <= 4 || mode >= 0){
System.out.println("Quit");
Restart_Game();
}
} else if(restart == 'n'|| restart == 'N'){
System.out.println("Thank you for playing");
System.exit(0);
}
}
private static int randIt(int max) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}

Your "Game" don't have a clue of the actual range, even if you have a parameter call "max", it is only the value to found, you could renamed it or you could really send the maximum value accepted :
Start_Game(15);
And let the game generate a random value based on that. You have the max value and the random value to found. Easy to check your case now.
public static int Start_Game(int max){
int toFind = randInt(max);
do{
GuessNum = input.nextInt();
if(GuessNum > max){
System.out.println("Out of range");
} else if(GuessNum == toFind ){
System.out.println("You WIN");
break;
}else if(GuessNum > toFind ){
System.out.println("BIG");
life--;
System.out.println("life: " + life);
}else if(GuessNum < toFind ){
System.out.println("SMALL");
life--;
System.out.println("life: " + life);
}
}while(life != 0);
}
Note : You should rename your method and variable, JAVA has a convention (like other language), don't name a variable starting with a uppercase for instance.
public static int startGame(int max){
or
int guessNum;

Related

Java beginner -Trying to let player quit the game

I'm a beginner making a guessing game and I am trying to let the player quit the game by making their guess -1. Currently, if I enter -1 it says Too low and asks me to keep guessing and the player cannot quit the game until they guess the number.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
char choice;
do {
int randomNum = (int) (Math.random() * 100 + 1);
int guess = 0;
while (guess != randomNum) {
System.out.println("Guess a number between 1-100");
guess = scan.nextInt();
if (guess > randoomNum) {
System.out.println("Too high.");
}
else if (guess < randoomNum) {
System.out.println("Too low.");
}
else if (guess > 0) {
System.exit(0);
System.out.println("GAME OVER");
System.out.println("the number was " + randomNum + ".");
}
else {
System.out.println("Correct! Well done!");
}
}
System.out.println("\nPlay again? (Y/N)");
choice = scan.next() .charAt(0);
} while (choice == 'Y' | choice =='y');
System.out.println("GAME OVER");
}
The existing code needs to be modified slightly: the condition with exit should be checked before comparing to the randomNum.
Other issues to be addressed:
Use input for Scanner instance
Perform System.exit after printing goodbye message
Scanner input = new Scanner(System.in);
char choice;
do {
int randomNum = (int) (Math.random() * 100 + 1);
int guess = 0;
while (guess != randomNum) {
System.out.println("Guess a number between 1-100, or -1 to exit");
guess = input.nextInt();
if (guess == -1) {
System.out.println("GAME OVER");
System.out.println("the number was " + randomNum + ".");
System.exit(0);
}
if (guess > randomNum) {
System.out.println("Too high.");
}
else if (guess < randomNum) {
System.out.println("Too low.");
}
else {
System.out.println("Correct! Well done!");
}
}
System.out.println("\nPlay again? (Y/N)");
choice = input.next().charAt(0);
} while (choice == 'Y' || choice =='y');
System.out.println("GAME OVER");

How do I use the "return" value of one method in another method

I am currently working on this project that plays the high low dice game. I am stuck on how to use the returned char from getHighLow and the returned int from getBet and getRoll in determineWinnings. This is my first year learning Java currently, so any help would be appreciated. Thank you in advance for any help you can give!
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int currentPool = 100;
getBet(keyboard, currentPool);
getHighLow(keyboard);
getRoll();
>> determineWinnings(highLow, userBet, rollSum);
}
// Given a Scanner and a current maximum amount of money, prompt the user for
// an integer representing the number of dollars that they want to bet. This
// number must be between 0 and to maximum number of dollars. If the user enters
// a number that is out of bounds, display an error message and ask again.
// Return the bet to the calling program.
private static int getBet(Scanner inScanner, int currentPool) {
int userBet = -1;
while (userBet == -1) {
inScanner = new Scanner(System.in);
System.out.println("You have $" + currentPool);
System.out.println("Enter an amount to bet (0 to quit): ");
userBet = inScanner.nextInt();
if (userBet > currentPool || userBet < 0) {
System.out.println("Your bet MUST be between 0 and " + currentPool + " dollars");
userBet = -1;
}
if (userBet == 0) {
System.out.println("You have " + currentPool + " dollars left.");
System.out.println("Goodbye!");
}
}
return userBet;
}
// Given a Scanner, prompt the user for a single character indicating whether
// they
// would like to bet High ('H'), Low ('L') or Sevens ('S'). Your code should
// accept
// either capital or lowercase answers, but should display an error if the user
// attempts
// to enter anything but one of these 3 values and prompt for a valid answer.
// Return the character to the calling program.
private static char getHighLow(Scanner inScanner) {
Scanner keyboard = new Scanner(System.in);
int i = 0;
String userChoice = "";
while (i == 0) {
System.out.println("High, low or sevens (H/L/S): ");
userChoice = keyboard.nextLine();
if (userChoice.length() > 1 || (userChoice.charAt(0) != 'H' && userChoice.charAt(0) != 'h'
&& userChoice.charAt(0) != 'L' && userChoice.charAt(0) != 'l' && userChoice.charAt(0) != 'S'
&& userChoice.charAt(0) != 's')) {
System.out.println("ERROR: You must type H, L, or S.");
} else {
i++;
}
}
char highLow = 'N';
if (userChoice.charAt(0) == 'H' || userChoice.charAt(0) == 'h') {
highLow = 'H';
} else if (userChoice.charAt(0) == 'L' || userChoice.charAt(0) == 'l') {
highLow = 'L';
} else {
highLow = 'S';
}
return highLow;
}
// Produce a random roll of a single six-sided die and return that value to the
// calling
// program
private static int getRoll() {
int dieOne = (int) (Math.random() * 6 + 1);
System.out.println("Die 1 rolls: " + dieOne);
int dieTwo = (int) (Math.random() * 6 + 1);
System.out.println("Die 2 rolls: " + dieTwo);
int rollSum = dieOne + dieTwo;
System.out.println("The total of two dice is: " + rollSum);
return rollSum;
}
// Given the choice of high, low or sevens, the player's bet and the total
// result of
// the roll of the dice, determine how much the player has won. If the player
// loses
// the bet then winnings should be negative. If the player wins, the winnings
// should
// be equal to the bet if the choice is High or Low and 4 times the bet if the
// choice
// was Sevens. Return the winnings to the calling program.
private static int determineWinnings(char highLow, int bet, int roll) {
int highLowValue = 0;
int winnings = 0;
if (highLow == 'H') {
highLowValue = 8;
} else if (highLow == 'L') {
highLowValue = 6;
} else {
highLowValue = 7;
}
if (roll >= 8 && highLowValue == 8) {
winnings = bet;
System.out.println("You won " + winnings + " dollars!");
} else if (roll <= 6 && highLowValue == 6) {
winnings = bet;
System.out.println("You won " + winnings + " dollars!");
} else if (roll == 7 && highLowValue == 7) {
winnings = bet * 4;
System.out.println("You won " + winnings + " dollars!");
} else {
winnings = -1 * bet;
}
return winnings;
}
You can assign the output of each method to variable or call methods directly on determineWinnings.
plan 1)
int userBet = getBet(keyboard, currentPool);
char highLow = getHighLow(keyboard);
int roll = getRoll();
determineWinnings(highLow, userBet, roll);
plan 2)
determineWinnings(getHighLow(keyboard), getBet(keyboard, currentPool), getRoll());
There are following approaches to get the result of one method to another.
Pass result of one method to another
Define private/static members
Better way would be passing result of one method to another method.

Java HiLo program stops

Right now im making a HiLo game in java and i have a few problems, not sure tho if im doing it right since im very new into java.
I having problem with getting the two ints "answer" and "guess" to the 3rd method.
and i must use 3 methods in this task.
Method 1: asking for what lvl the user wants.
Method 2: The program picks a random number between max and lets the user guess.
Method 3: Will see if the guess is == to answer and if not, it lets the user to try again. and at the same time i have to save all the tries from the user.
import java.util.Scanner;
import java.util.Random;
public class oneagain {
public static void main(String[] args) {
System.out.println("Welcome HiLo!");
System.out.println("What lvl?");
System.out.println("1. Easy (1-10)");
System.out.println("2. Medium (1-100)");
System.out.println("3. Hard (1-1000)");
Scanner sc = new Scanner(System.in);
int choice = sc.nextInt();
int tries = (playGame(choice));
}
public static int playGame(int choice) {
Scanner sc = new Scanner(System.in);
int tries = 0;
if (choice == 1) {
System.out.println("Guess a number between 1 and 10");
int answer = (int) (Math.random() * 11) + 1;
int guess = sc.nextInt();
}
if (choice == 2) {
System.out.println("Guess a number between 1 and 100");
int answer = (int) (Math.random() * 101) + 1;
int guess = sc.nextInt();
}
if (choice == 3) {
System.out.println("Guess a number between 1 and 1000");
int answer = (int) (Math.random() * 1001) + 1;
int guess = sc.nextInt();
}
return tries;
}
public static void giveResponse(int answer, int guess) {
if (choice == 1) {
int tries = 0;
Scanner sc = new Scanner(System.in);
boolean y = false;
while (y == false) {
guess = sc.nextInt();
tries++;
if (guess == answer) {
y = true;
} else if (guess < answer) {
System.out.println("Guess was too low!");
System.out.println("Guess a number between 1 and 10:");
} else if (guess > answer) {
System.out.println("Guess was too high!");
System.out.println("Guess a number between 1 and 10:");
} else if (guess == answer) {
System.out.println("Score!");
System.out.println("You succeeded in " + tries + " attempt");
}
if (choice == 2) {
while (y == false) {
guess = sc.nextInt();
tries++;
if (guess == answer) {
y = true;
} else if (guess < answer) {
System.out.println("Guess was too low!");
System.out.println("Guess a number between 1 and 100:");
} else if (guess > answer) {
System.out.println("Guess was too high!");
System.out.println("Guess a number between 1 and 100:");
} else if (guess == answer) {
System.out.println("Score!");
System.out.println("You succeeded in " + tries + " attempt");
}
if (choice == 3) {
while (y == false) {
guess = sc.nextInt();
tries++;
if (guess == answer) {
y = true;
} else if (guess < answer) {
System.out.println("Guess was too low!");
System.out.println("Guess a number between 1 and 100:");
} else if (guess > answer) {
System.out.println("Guess was too high!");
System.out.println("Guess a number between 1 and 100:");
} else if (guess == answer) {
System.out.println("Score!");
System.out.println("You succeeded in " + tries + " attempt");
}
}
}
}
}
}
}
}
}

How to execute a block of code without bypassing another one? Java

The title is probably not very informative. But here's the deal.
I want the user to execute a code if it's the second time he is passing there. What I did, was making a if statement, but now I've noticed, that with that, the rest isn't being executed.
Scanner input = new Scanner(System.in);
Random dice = new Random();
int counter = 1;
boolean playing = true;
boolean firstTimmer = true;
boolean got = true;
System.out.println("Welcome to numberMind! From 0 to x, you'll try to guess the random number!");
System.out.println("To quit, guess \"-1\".");
System.out.print("Insert x: ");
int x = 1+input.nextInt();
int objective = dice.nextInt(x);
System.out.print("Ok, I'm ready! What's your first guess? ");
int guess = input.nextInt();
while (playing){
if (guess == -1){
playing = false;
break;
}else if (!firstTimmer){
got = true;
System.out.print("Do you want to change the number range? Yes(1) No(2)");
guess = input.nextInt();
if (guess == 1){
System.out.print("Insert the new x: ");
x = 1+input.nextInt();
}else if(guess == 2){
System.out.println("Let's go then!");
}else{
System.out.print("I didn't ask for that number did I? x won't change.");
}
}else{
while(got){
if (objective == guess){
firstTimmer = false;
System.out.println("You guessed it in "+counter+" times!");
counter = 1;
System.out.print("Do you want to paly again? Yes(1) No(2) ");
guess = input.nextInt();
if (guess == 1){
System.out.println("Great! Here we go...");
got = false;
break;
}else if (guess == 2){
System.out.print("Thanks for playing!");
got = false;
playing = false;
}else{
System.out.println("We didn't ask for that. NOW YOU PLAY SOME MORE!");
got = false;
break;
}
break;
}else if (guess == -1){
System.out.println("You quited :(");
break;
}else if (guess == -2){
System.out.println("The correct answer is "+ objective);
}else if (counter >= 5 && (counter -5) % 3 == 0 ){
if (objective % 2 == 0){
System.out.println("The number is pair.");
}else{
System.out.println("The number is odd.");
}
}
System.out.println("You have tryed " + counter++ + " times.");
System.out.print("What's your guess? ");
guess = input.nextInt();
}
}
}
The code I want to run is after the last else. I'm not seeing anything to solve it. Thank you
Well start by asking yourself when the else will be fulfilled: when guess != -1 and firstTimmer == true. You don't ever set firstTimmer, which needs to be set to true to pass through the the else block. You also need to remove the break in your else if, otherwise it will never reach the else on the next iteration.
Also, having both playing = false and break in your if statement is redundant. Both will do the same thing individually.
while (playing){
if (guess == -1){
playing = false;
break;
}else if (!firstTimmer){
got = true;
System.out.print("Do you want to change the number range? Yes(1) No(2)");
guess = input.nextInt();
if (guess == 1){
System.out.print("Insert the new x: ");
x = 1+input.nextInt();
}else if(guess == 2){
System.out.println("Let's go then!");
}else{
System.out.print("I didn't ask for that number, x won't change.");
}
firstTimmer = true;
//break;
}else{
int counter = 0;
while(playing) {
counter++; //First iteration: was zero, now 1
if(counter == 2) {
//Do some special thing
}
}
(One) standard pattern for this sort of thing is:
boolean firstTime = true;
boolean playing = true;
int guess = 0;
while (playing) {
if (guess == -1) {
playing = false;
// NOTE: break is redundant with playing flag, here
} else if (!firstTime) {
got = true;
System.out.print("Do you want to change the number range? Yes(1) No(2)");
guess = input.nextInt();
if (guess == 1) {
System.out.print("Insert the new x: ");
x = 1+input.nextInt();
} else if(guess == 2) {
System.out.println("Let's go then!");
} else {
System.out.print("I didn't ask for that number, x won't change.");
}
firstTime = false;
} else {
//... do other work here.
}
}
Also, the pattern mentioned by aliteralmind is a more flexible version of the above, allowing you to present a different option for every "visit" through the loop. I can describe further if necessary, with a complete example.
You should try to solve a one problem per time in your code.
Now you have a lot of complicated code that is hard to read and work with.
The answer to your question, regarding the first time visit. Just move it before loop and then start the loop if necessary.
Try to divide the problem in sub programs (methods) and the solve them by once.
displayWelcomeScreen();
preapreGameContext();
do {
if(doUserWantToChange()) {
changeTheGameContext();
}
int gues = askForGues();
hasUserGuesCorrectly();
} while(isTheGameOn());
The final code should look more alike the example above.

How to keep requesting user to select a valid option?

So, the user has to choose a number between 1 and 3. Otherwise, they're told to try again. If the user tries a number less than 1 or greater than 3, whatever number they chose gets stored in the "choice" variable and causes the program to continue to run when it should just stop. I assumed there would be an easy solution, but apparently it's beyond me as a beginner. The obvious thing to me would be to somehow clear or empty the value that has been assigned to "choice" after the unsuccessful user input. Is that possible?
import java.util.Scanner;
public class Furniture2Test {
public static void main(String[] args) {
wood();
} // end main
public static void wood() {
int choice;
int pine = 1;
int oak = 2;
int mahogany = 3;
int pineCost = 100;
int oakCost = 225;
int mahoganyCost = 310;
Scanner keyboard = new Scanner(System.in);
System.out.println("What type of table would you like?");
System.out.println("1. pine");
System.out.println("2. oak");
System.out.println("3. mahogany");
choice = keyboard.nextInt();
if (choice == 1) {
choice = pineCost;
} else if (choice == 2) {
choice = oakCost;
} else if (choice == 3) {
choice = mahoganyCost;
} else if (choice > 3 || choice < 1) {
System.out.println("Try again.");
choice = -1;
wood();
}
System.out.println("That will be $" + choice + ".");
size(choice);
} // end wood
public static void size(int choice) {
int sizeChoice;
int large = 35;
Scanner keyboard = new Scanner(System.in);
System.out.println("What size will that be?");
System.out.println("1. large");
System.out.println("2. small");
sizeChoice = keyboard.nextInt();
if (sizeChoice == 1)
System.out.println("That will be $" + (choice + large) + ".");
else if (sizeChoice == 2)
System.out.println("That will be $" + choice);
else
System.out.println("Please, enter either a 1 or a 2.");
} // end size
}
Your requirement can be done easily with do...while loop. Sample code is as follows:
do{
System.out.println("Choose option between 1 and 3");
choice = keyboard.nextInt();
}while(!(choice > 3 || choice < 1));
if (choice == 1) {
choice = pineCost;
} else if (choice == 2) {
choice = oakCost;
} else if (choice == 3) {
choice = mahoganyCost;
}
Hope this helps.
//put the menu logic
while(choice > 3 || choice < 1) {
//put your try again logic.
}
//can only exit the while loop if the number is 1, 2, or 3, so put your output statement down here after the while loop
import java.util.Scanner;
public class Furniture2Test
{
public static void main(String[] args)
{
wood();
} // end main
public static void wood()
{
int choice;
int pine = 1;
int oak = 2;
int mahogany = 3;
int pineCost = 100;
int oakCost = 225;
int mahoganyCost = 310;
Scanner keyboard = new Scanner(System.in);
System.out.println("What type of table would you like?");
System.out.println("1. pine");
System.out.println("2. oak");
System.out.println("3. mahogany");
choice = read_range(keyboard, 1, 3);
if(choice == 1)
{
choice = pineCost;
}
else
if(choice == 2)
{
choice = oakCost;
}
else
if(choice == 3)
{
choice = mahoganyCost;
}
else
if(choice > 3 || choice < 1)
{
System.out.println("Try again.");
choice = -1;
wood();
}
System.out.println("That will be $" + choice + ".");
size(choice);
} // end wood
public static void size(int choice)
{
int sizeChoice;
int large = 35;
Scanner keyboard = new Scanner(System.in);
System.out.println("What size will that be?");
System.out.println("1. large");
System.out.println("2. small");
sizeChoice = read_range(keyboard, 1, 2);
if(sizeChoice == 1)
System.out.println("That will be $" + (choice + large) + ".");
else
if(sizeChoice == 2)
System.out.println("That will be $" + choice);
else
System.out.println("Please, enter either a 1 or a 2.");
} // end size
private static int read_range (Scanner scanner, int low, int high) {
int value;
value = scanner.nextInt();
while (value < low || value > high) {
System.out.print("Please enter a value between " + low + " and " + high + ": ");
value = scanner.nextInt();
}
return value;
}
} // end class
whatever number they chose gets stored in the "choice" variable and causes the program to continue to run when it should just stop//
the program is contining to run because you are calling wood() if(choice > 3 || choice < 1)
if you want it to stop remove the wood() call
if you also want to clear the value for choice(instead of -1) you can assign it to null
choice is a local variable to the method wood, you are making a recursive call to wood when the user makes a wrong choice. This is an interesting design choice and probably not the best in this case.
When you call wood again, choice is rest (in this to unknown value until it is assigned value from the user).
Now the problem occurs when the wood method exists...each time it returns to the caller, it will call size(choice), where choice is -1 (because that's what you set it to before calling wood again).
You should be using a while-loop instead of recursive calls
You should never call size(choice) with anything other then a valid choice
Take a look at The while and do-while statement for more details

Categories

Resources