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
Related
Our task was to create a guessing game, where the computer would generate a number and the user was prompted to guess. We were to create a method to play only one game, and then create a while loop in the main to make the game playable again. In the end, we need to show statistics. I'm having trouble with showing the "best game." That is a game where the amount of guesses is the least.
Here is the code:
import java.util.Random;
import java.util.Scanner;
public class GuessingGame {
public static final int MAX = 100;
// This is the main. Here we can see a do/while loop
// and a few variables that were created to compliment it.
public static void main(String[] args) {
Random rand = new Random();
Scanner console = new Scanner(System.in);
intro();
String s = "";
int totalGames = 0;
int totalGuess = 0;
do {
totalGuess = game(console);
System.out.print("Do you want to play again? ");
s = console.next();
totalGames++;
} while (s.equals("y") || s.equals("Y") || s.equals("Yes") ||
s.equals("yes") || s.equals("Yes"));
totalGuess = totalGuess;
statistics(totalGames, totalGuess);
}
// This method prints out the intro.
public static void intro() {
System.out.println("This program allows you to play a guessing
game.");
System.out.println("I will think of a number between 1 and");
System.out.println(MAX + " and will allow you to guess until");
System.out.println("you get it. For each guess, I will tell you");
System.out.println("whether the right answer is higher or lower");
System.out.println("than your guess.\n ");
}
// This method plays the game only once. It's later used in the main.
// Returns the
// number of guesses for one game.
public static int game(Scanner console) {
Random rand = new Random();
int random = rand.nextInt(MAX) + 1;
System.out.println("I'm thinking of a number between 1 and " + MAX + "
... (it's " + random + " )");
System.out.print("Your guess? > ");
int guess = console.nextInt();
int count = 0;
do {
if ((random - guess) > 0) {
System.out.println("It's higher.");
System.out.print("Your guess? > ");
guess = console.nextInt();
count++;
}
else if ((random - guess) < 0) {
System.out.println("It's lower.");
System.out.print("Your guess? > ");
guess = console.nextInt();
count++;
}
else if (random == guess) {
count++;
}
} while (random != guess);
if (count == 1) {
System.out.println("You got it right on the first guess!!");
}
else {
System.out.println("You got it right in " + count + " guesses.");
}
return count;
}
// This method prints out the statistics.
public static void statistics(int x, int y) {
System.out.println("total games = " + x);
System.out.println("total guesses = " + (y));
System.out.println("guesses/game = ");
System.out.println("best game = ");
}
}
Have a look when totalGuess is assigned:
public static void main(String[] args) {
Random rand = new Random();
Scanner console = new Scanner(System.in);
intro();
String s = "";
int totalGames = 0;
int totalGuess = 0;
// ^ Initialized to zero
do {
totalGuess = game(console);
// ^ Assigned (not added) to the return value from game.
// Did you mean: totalGuess += game(console); ?
System.out.print("Do you want to play again? ");
s = console.next();
totalGames++;
} while (s.equals("y") || s.equals("Y") || s.equals("Yes") ||
s.equals("yes") || s.equals("Yes"));
totalGuess = totalGuess;
// ^ Assigned to itself. No action.
statistics(totalGames, totalGuess);
}
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;
My program should execute these steps:
Generate random no from 0 to 100.
Display random no and ask user enter (h/l/c)? (user have to enter one of them).
If it is correct ask user if they like to play again (y/n)? (user must answer (y/n))
I was able to execute Question no.1. Question no.2, random no display but I am unable to type character (h/l/c). Also, I am not able to ask player if they want to play again or not?
Here is what I have done:
import java.util.Random;
import java.util.Scanner;
public class NumberGuessingGame {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int number;
int guess = 0;
int min = 0;
int max = 100;
int answer= (min+max);
number = (int) (Math.random() *100 +1);
System.out.println("Guess a number between 1 and 100.");
//Ask user to type higher 'h', lower 'l' and correct 'c'.
System.out.println("Is it " + number + " ?" + " (h/l/c): " );
//
guess = 50;
while (guess <= 7)
{
System.out.println( "It is: " + guess + "?" + "(h/l/c) : " );
//Type 'h' if guess is high, 'l' for low and 'c' for correct.
if(answer == 'h')
{
max = guess -1;
min = 0;
guess = ((max = min)/2) + min;
guess++;
} else if (answer == 'l')
{
max = 100;
min = guess + 1;
guess = ((max+min)/2);
guess++;
} else if (answer == 'c');
}
System.out.println("Great! Do you want to play again? (y/n): ");
if(answer == 'y')
{
System.out.println("Guess a number between 1 and 100.");
//else prompt another question with if else
} else{
System.exit(0);
}
}
}
Your program does not accept any user input about if the guess is too low or too high.
You declared "answer" with an equation so it should accept a number.
answer would require a char or String value.
answer = keyboard.nextChar(); //read a char
answer = keyboard.nextLine(); //read a String
I believe I may need to use for instead of while, I am unsure on how fix this. When I try to research this all I can find is in relation to "sum of arrays" My sum keeps coming out to equal 10 although I have declared the values. Can someone help? Thanks
public class OnlinePurchases {
public static void main(String[] args) {
// TODO code application logic here
String sName = " ";
int nChoices = 0;
int nChoice1 = 249;
int nChoice2 = 39;
int nChoice3 = 1149;
int nChoice4 = 349;
int nChoice5 = 49;
int nChoice6 = 119;
int nChoice7 = 899;
int nChoice8 = 299;
int nChoice9 = 399;
int nSum = 0;
final int SENTINEL = 10;
int nCount = 0;
Scanner input = new Scanner(System.in);
System.out.print("Please enter your name : ");
sName = input.nextLine();
System.out.println("BEST PURCHASE PRODUCTS \n");
System.out.println("1. Smartphone $249");
System.out.println("2. Smartphone case $39");
System.out.println("3. PC Laptop $1149 ");
System.out.println("4. Tablet $349");
System.out.println("5. Tablet case $49");
System.out.println("6. eReader $119");
System.out.println("7. PC Desktop $899");
System.out.println("8. LED Monitor $299");
System.out.println("9. Laser Printer $399");
System.out.println("10. Complete my order");
System.out.println("");
System.out.print("Please select an item from the menu above : ");
nChoices = input.nextInt();
while (nChoices != SENTINEL) {
System.out.print("Please select another item from the menu above : ");
nCount++;
nChoices = input.nextInt();
if (nChoices == 1) {
nChoices = nChoice1;
} else if (nChoices == 2) {
nChoices = nChoice2;
} else if (nChoices == 3) {
nChoices = nChoice3;
} else if (nChoices == 4) {
nChoices = nChoice4;
} else if (nChoices == 5) {
nChoices = nChoice5;
}
}
nSum = nSum + nChoices;
System.out.println("Price of Items Ordered : " + nSum);
System.out.println("Total Items Ordered : " + nCount);
}
}
Your while loop is fine.
Your problem is occuring because when a choice is selected you are not actually adding to your nSum variable. So when it comes to printing the sum out you are actually printing
nSum = nSum + nChoices = nSum = 0 + 10
This is why you are constantly getting the value 10.
To fix this replace your nChoices if statement with
if (nChoices == 1) {
nSum += nChoice1;
} else if (nChoices == 2) {
nSum += nChoice2;
} else if (nChoices == 3) {
nSum += nChoice3;
} else if (nChoices == 4) {
nSum += nChoice4;
} else if (nChoices == 5) {
nSum += nChoice5;
}
You are using the variable nChoices to check for the number that is entered. When you want to stop the program, 10 is the last number that is entered so 10 is what is added to nSum. To fix this you should first check for the first input before you enter the while loop and then check the input at the end of the while loop so that if 10 is chosen it won't go through the loop again. Also, under each if/else if statement you should use:
nSum += nChoiceWhatever //"Whatever" being the number correlated to your prices
I am writing a program that will ask the user to guess a random number 6 times. The program has to ask if they want to play again and will keep a running total of the wins/losses.
How would I have the program rerun?
heres the code:
import java.util.Scanner;
import java.util.Random;
public class Project {
public static void main(String[] args) {
String input;
double guess = 0;
int number;
double wins = 0;
double losses = 0;
String repeat;
Scanner keyboard = new Scanner(System.in);
Random randomNumbers = new Random();
System.out.println("Welcome to Higher/Lower!");
System.out.println("Enter your name: ");
input = keyboard.nextLine();
while(input.equalsIgnoreCase("yes")); {
number = randomNumbers.nextInt(100) + 1;
System.out.println("I've chosen my number, " + input + "You only have 6 tries, good luck!"); }
for(int num = 1; number != guess && number <= 6; num++) {
System.out.println("Enter guess " + num + ":");
guess = keyboard.nextDouble();
if(guess < number)
System.out.println("higher.");
else if(guess > number)
System.out.println("lower.");
else
System.out.println("Congratulations!"); }
if(guess == number) {
System.out.println("You guesses my number!"); wins++; }
if(guess != number) {
System.out.println("Sorry, " + input + " my number was " + number +
"You lose!"); losses++; }
System.out.println("Do you want to play again? (Yes/No): ");
repeat = keyboard.nextLine();
if(input.equalsIgnoreCase("no")); {
System.out.println("Thanks for playing!"); }
System.out.println(wins + " wins");
System.out.println(losses + " losses");
}
}
It is skipping over asking me if i want to play again or not and i dont know what kind of loop to use
Wihtout your code, I'm assuming this is what you need.
boolean doContinue = true;
do {
//guess random number 6 times
//do you want to continue?
// yes -> doContinue = true;
// no -> doContinue = false;
} while (doContinue );
I would suggest making your loop a do-while loop like this:
do {
for (int i=0; i<6; i++){
/*
insert code for the guessing/checking/etc.
*/
}
System.out.print("Would you like to continue? [Y/n] ");
} while (scan.next().toUpperCase().charAt(0) != 'Y');