Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I'm new at java and i tried to make a Guess The Number game.
When the loop starts, i want to check if the user has any tries left.
if (remain > 1);
then after each end of the loop I want to subtract 1 from the tries.
I also tried to gather 1 after each loop ends.
byte tries = 5, remain=(byte)(--tries);
When user is out of tries i want to break the loop and break the game:
else if (remain == 0){
System.out.println("You haven't guessed the number!");
break;
}
Here's my code:
public class Master{
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
double number = (byte)(Math.random() * 21);
while(true){
// User input
System.out.print("Choose a number between 1 and 21 :");
byte user = scanner.nextByte();
byte tries = 5, remain=(byte)(--tries);
System.out.println(remain);
if (remain > 1);
//game
if (user==number){
System.out.println("You have guessed the number!");
break;
} else if (user < number)
System.out.println("You are lower than the number!");
else if (user > number)
System.out.println("You are higher than the number!");
//Break if user is out of tries
else if (remain == 0){
System.out.println("You haven't guessed the number!");
break;
}
}
}
}
Code works perfectly but it won't break when user is out of tries.
tries variable should be initialized outside the while loop and the if statement was being closed using a ';'
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
double number = (byte)(Math.random() * 21);
byte tries = 5; // tries should be initialized outside the loop
while(true){
// User input
System.out.print("Choose a number between 1 and 21 :");
byte user = scanner.nextByte();
byte remain=(byte)(--tries);
System.out.println(remain);
if (remain > 1) { // You were using ; and this if statement was closed
//game
if (user==number){
System.out.println("You have guessed the number!");
break;
} else if (user < number)
System.out.println("You are lower than the number!");
else if (user > number)
System.out.println("You are higher than the number!");
}
//Break if user is out of tries
else if (remain == 0){
System.out.println("You haven't guessed the number!");
break;
}
}
}
I think you are misunderstanding a lot of concepts. Here's a commented version :
public class Master {
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
// The number to found
double numberToFound = (byte)(Math.random() * 21);
// The user number will be stored here
byte userInput = 0;
// The number of tries left
byte tryLeft = (byte) 5;
do {
// Ask the User an number
System.out.print("Choose a number between 1 and 21 :");
userInput = scanner.nextByte(); // Store it
// Test the number
if (userInput > numberToFound) {
System.out.println("You are lower than the number!");
} else {
System.out.println("You are higher than the number!");
}
tryLeft--; // We remove one try
} while(tryLeft > 0 && userInput != numberToFound); // We loop until there are no more try OR we found the number
// Last time check (we check why we exited the loop)
// The user found the number
if (numberToFound == userInput)
System.out.println("You have guessed the number!");
else // The user has no more tries left
System.out.println("You haven't guessed the number!");
}
}
You should avoid using while(true) if you have a breaking condition for better readability.
You can try this code.
I changed some datatypes and added the decreasing of the remain variable inside the loop.
public class Master{
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
int number = (int)(Math.random() * 21);
int tries = 5;
int remain = tries;
while(true){
System.out.print("Choose a number between 1 and 21:");
int user = scanner.nextInt();
// User input
System.out.println(remain);
if (remain > 1) {
//game
if (user==number){
System.out.println("You have guessed the number!");
break;
} else if (user < number)
System.out.println("You are lower than the number!");
else if (user > number)
System.out.println("You are higher than the number!");
--remain;
}
//Break if user is out of tries
else if (remain == 0){
System.out.println("You haven't guessed the number!");
break;
}
}
}
}
First of all, you can check if the "remain" is bigger than 0 and not 1, and your code will do the job as you planned (and you don't need to check == 0 at the else) :)
Second of all small comments to make your code more arranged:
Work with parameters that are comfortable to you like int (easier to debug and work with) you should use byte only if the code really needs it.
Move parameters that you use only to check them outside the loop like tries (think on that you will define this variable on every loop iteration and you don't need to).
Add to the params you are not going to change (like tries & number after you moved outside the loop) final it will be more clear that you are not going to change this param anymore.
Other than that looks great, good luck! :)
Related
I'm new to Java programming and taking a college course where I have an assignment to create a Hi/Lo guessing game. The game provides up to 5 attempts for the user to input a number between 1 and 100 (inclusive). The program must provide the logic back of whether the answer is too low, too high or correct. The program must provide the option to play again after either winning or the 5 failed attempts.
I've recreated this program about 10 times :(. I cannot get he logic to work to follow the instructions above. I cannot stop the tries at 5 attempts... and I cannot get the program to execute a new game.
Any help is greatly appreciated. I've spent countless hours writing and re-writing this code with MANY different results - but not the intended ones.
This is my first time posting so, I apologize if the format to post is not correct.
I've looked through more forums and examples than I care to admit and none of code I've reviewed and tried implementing have given me the results of limiting the user input to 5 tries each time and ability to play again multiple times.
Here is my code:
public class HiLoGuessingGame {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
//Initialize scanner and random number gennerator
Scanner input = new Scanner(System.in);
Random generator = new Random();
//State the rules of the game
System.out.println("The Hi-Lo Guessing Game. Guess a number between 1-100");
System.out.println("You have 5 attempts!");
/* define the variable Guess (user iput)
define the variable Answer (random generator)
define the variable Counter (track number of tries and limit to 5)
define the variable PlayAgain (Y/N question)*/
int guess = 0;
int answer = generator.nextInt(100)+1;
int counter = 1;
String playAgain;
boolean gameOver = false;
//Ask the Hi-Lo question - pick number 1-100 (inclusive)
//Provide feedback answer too high, too low or you win!
//Limit number of tries in the game to 5
while (guess != answer) {
System.out.print("Enter your guess: ");
guess = input.nextInt();
counter++;
if (guess < answer) {
System.out.println("Your guess " + guess + " is too low. Try again");
System.out.println("This is attempt: " + counter);
} else if (guess > answer) {
System.out.println("Your guess " + guess + " is too high. Try again");
System.out.println("This is attempt: " + counter);
} else if (guess == answer) {
System.out.println("Your guess " + guess + " is correct! You win!");
System.out.println();
System.out.println("Would you like to play again (Y/N)?");
playAgain = input.next();
}
}
if (counter ==6) {
System.out.println("Sorry, you've reached your max atttempts.");
System.out.println("Would you like to play again (Y/N)?");
playAgain = input.next();
}
// Play again logic
boolean isValid;
do {
System.out.print("Would you like to play again (Y/N)?");
playAgain = input.next().toUpperCase();
isValid = playAgain.equals("Y") || playAgain.equals("N");
playAgain = input.next();
counter = 1;
if ( !isValid ) {
System.out.println("Error, please enter Y or N");
System.out.println();
}
} while (!isValid);
}
}
You can add an extra condition to your while-loop:
while (guess != answer && counter < 5) {
// ...
}
Alternatively, you can break the loop when you get a right answer:
while (counter < 5) {
// ...
if (answer == guess){
// ...
break;
}
}
I am trying to develop a simple high low game that asks the user after playing if they would like to play again. If I remove the outer while loop the logic of the inner loop does exactly what I want it to do, however I am unsure how to wrap the inner loop with an outer loop that will ask the play again question and if the answer is yes put them back into the inner loop. Below is my code.
import java.util.Scanner;
import java.util.Random;
public class HiLoGuess {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in); // Creates scanner object.
Random numb = new Random(); // Creates an instance of the random class.
int guess = -1; // Placeholder for users guess.
int answer = numb.nextInt(100)+1; // Generates a random number for the game.
int count = 0; // Placeholder for the guess counter.
int sentinel = 0; // Placeholder for players answer as to whether they want to play again or not.
String newgame = "y";
while (newgame.equalsIgnoreCase("y"))
{
while (guess != sentinel && guess != answer) //Loop that ends when user enters a zero.
{
System.out.println ("Enter a number between 1-100 or 0 to quit");
guess = scan.nextInt();
count++;
if (guess < answer && guess > 0 )
{
System.out.println("Your guess is too low, guess again");
}
else if (guess > answer)
{
System.out.println ("Your guess is to high, guess again");
}
else if (guess == answer)
{
System.out.println ();
System.out.println ("You guessed correctly, you win!!!");
System.out.println ("It took you " + count + " guesses");
}
}
System.out.print();
System.out.println("Play another game: y or n?");
newgame = scan.nextLine();
}
}
}
You need to put these initializations into the outer loop:
int guess = -1;
int answer = numb.nextInt(100)+1;
int count = 0;
Otherwise they keep the value from the last game and the inner loop will not be executed any more.
you never reset your guess, sentinel, or answer variables
so (guess != sentinel && guess != answer) always evaluates to false after the first time the game is played, and therefore the inner while loop never executes after the first game
while (guess != sentinel && guess != answer) //this is false after the first game because you don't reset variables
{ ...}
Update for OP comment:
to get your code to do what you want you need to add the resets between the outter and inner while loop like this
while (newgame.equalsIgnoreCase("y"))
{
guess = -1;
answer = numb.nextInt(100)+1;
count = 0;
while (guess != sentinel && guess != answer) //Loop that ends when user enters a zero.
{ ...}
}
Replace newgame = scan.nextLine(); by this : newgame = scan.next();
And you need to initialise your variables inside your while loop, so that the flag is reseted to false and the random generate new result to guess.
public class Game
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in); // Creates scanner object.
Random numb = new Random(); // Creates an instance of the random class.
String newgame = "y";
while (newgame.equalsIgnoreCase("y")) {
int count = 0; // Placeholder for the guess counter.
int guess = -1; // Placeholder for users guess.
int answer = numb.nextInt(100) + 1; // Generates a random number for the game.
int sentinel = 0; // Placeholder for players answer as to whether they want to play again or not.
while (guess != sentinel && guess != answer) // Loop that ends when user enters a zero.
{
System.out.println("Enter a number between 1-100 or 0 to quit");
guess = scan.nextInt();
count++;
if (guess < answer && guess > 0) {
System.out.println("Your guess is too low, guess again");
} else if (guess > answer) {
System.out.println("Your guess is to high, guess again");
}
else if (guess == answer) {
System.out.println();
System.out.println("You guessed correctly, you win!!!");
System.out.println("It took you " + count + " guesses");
}
}
System.out.println();
System.out.println("Play another game: y or n?");
newgame = scan.next();
}
}
}
I am currently trying to complete a program with multiple classes in java that will allow the user to input information to help him or her book tickets, accommodation, parking, etc for a rock festival. I have started with one of the classes 'accommodation' to return the correct input of the user to the main class, however, I have found when I run the program and enter option 3, it immediately loops continuously which I have to terminate. I have searched online for a way to stop the loop, and for it to return the correct inputted information to no avail, I would appreciate any help to a very new new noob, before this loop turns me loopy!
Below is my main class and the class 'accommodation'. thank you in advance and apologies for any messy coding I have, as I have been trying various options as I have said before.
import java.util.Scanner;
import java.util.InputMismatchException;
public class clydeRockfest {
public static void main(String[] args) {
boolean quit = false;
Scanner in = new Scanner(System.in);
int choice; // Display the menu
int answer = 0;
Accommodation accommodation = new Accommodation();
//accommodation.getaccommodation();
do{
System.out.println("1\t Festgoers");
System.out.println("2\t Ticket");
System.out.println("3\t Accommodation");
System.out.println("4\t Transport");
System.out.println("5\t Parking");
System.out.println("0\t Quit");
System.out.println("Please enter your choice:");
//Get user's choice
choice=in.nextInt();
if(choice == 0)
quit=true;
//Display the title of the chosen module
switch (choice) {
break;
case 3: accommodation.getaccommodation();
System.out.println("You require " + answer + " accommodation.");
break;
case 0:
quit=true;
break;
default: System.out.println("Invalid choice, please choose again.");
} //end of switch
} //end of the main method
while(!quit);
} //end of class
}
public class Accommodation {
private String accommodation;
void getaccommodation(){
int no = 0; // no accommodation at all required
int self_Pitch = 0; // chosen if requiring a pitch
int tent = 0; // chosen if using a tent
int answer = 0;
int choice = 0;
boolean done = false;
System.out.println("Do you require accommodation?");
System.out.println();
// Answer validation loop
boolean validanswer = true;
while (!validanswer){
System.out.println("Enter:(1=NO, 2=SELF-PITCH, 3=TENT)");
System.out.println();
if(answer > 0 && answer < 4){
validanswer = true;
done = true;
}// ends if
else{
System.out.println();
System.out.println("That is not a valid answer, please choose again:");
System.out.println();
} // ends else
} //ends while
}
public void setaccommodation(String accommodation){
this.accommodation = accommodation;
}
Output:
Please enter your choice:
3
Do you require accommodation?
You require 0 accommodation.
1 Festgoers
2 Ticket
3 Accommodation
4 Transport
5 Parking
0 Quit
Please enter your choice:
you prime your loop by setting done=false but never set done = true so your loop will never end
You have two loops checking if user is done, and the condition of the first one (with the done) variable is never changed. Just remove this loop, and you should be fine.
Also, it looks like the condition for the second loop variable should be
if (answer > 0 && answer < 4)
to match your menu alternatives.
You never set done to true. It seems you may need to do it here:
if(answer >=0 && answer <=4){
validanswer = true;
done = true;
}
else{
//code
}
However, I'm not even sure you need that outer loop in the first place:
while(!done){
It seems redundant.
I stopped programming for a while now. Probably around 4 years, and I was just looking to mess around with it, so I decided to make a high:low number guessing game. (guess a number 1-100, program says if your guess is too high or too low) and I completely forgot how I would go about:
a) Once the user guesses the correct number, asking if they want to play again
b) If they don't guess the correct number (too high or too low), the program lets them guess again.
I understand that you would need loops, but I just forgot about how I would go about them
package highlow;
import java.util.Random;
import java.util.Scanner;
public class guessing {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
Random rand = new Random();
int tries;
int correctNum = rand.nextInt(100);
System.out.println("enter a number 1-100");
int guess1 = input.nextInt();
if(guess1 < correctNum){
System.out.println("number is too low!");
}
else if(guess1 > correctNum){
System.out.println("Number is too high!");
}
else if(guess1 == correctNum){
System.out.println("correct!");
}
else{
System.out.println("not a valid option");
}
}
}
You need to wrap everything in a while loop so that it keeps repeating until the user guesses correctly:
// Make the scanner, get the random number etc... Put all the setup and
// stuff you don't want to be repeated here
while (true) {
System.out.println("enter a number 0-99"); // Changed from 1-100 because rand.nextInt(100)
// returns a number between 0 and 99
// You can do correctNum += 1 to make it between 1 and 100
// But put this in before the while loop starts
int guess1 = input.nextInt();
if(guess1 < correctNum){
System.out.println("number is too low!");
}
else if(guess1 > correctNum){
System.out.println("Number is too high!");
}
else if(guess1 == correctNum){
System.out.println("correct!");
break; // <---- Add this, this will make the loop stop when the
//player gets the answer correct and therefore the program will end
}
else{
System.out.println("not a valid option");
}
}
While loops repeat whatever is inside them until the statement inside their () is false. In our case the loop will go forever because true is inside the () but with the break statement, the loop will end when the user guesses correctly.
package highlow;
import java.util.*;
public class guessing
{
public static void main (String [] args)
{
boolean wantstoplay = true;
while(wantstoplay)
{
play();
System.out.println("Would you like to play again?");
Scanner kb = new Scanner (System.In);
if ((kb.nextLine().equals("yes") || (kb.nextLine().equals("Yes"))
wantstoplay = true;
else
wantstoplay = false;
}
}
public void play()
{
boolean playing = true;
int correctNum = (int) ((Math.Random() *100) + 1);
//selects random double from [1,101) and then rounds down
int tries = 0;
while (playing)
{
Scanner input = new Scanner(System.in);
System.out.println("enter a number 1-100");
int guess = input.nextInt();
if(guess < correctNum){
System.out.println("number is too low!");
tries++;
}
else if(guess > correctNum){
System.out.println("Number is too high!");
tries++;
}
else if(guess == correctNum){
System.out.println("correct!");
if (tries > 1)
System.out.println("Congrats, you guessed the right number. It only took you " + tries + " attempts!");
else
System.out.println("You guessed it first try! good job");
}
else{
System.out.println("not a valid option");
}
}
}
}
Above is some sample code that might be helpful.
I suggest making a play method, and then calling it in your main method.
This makes your code more organized and readable, because now you'll get the functionalities you desired without having 1 messy method with 2 loops in it.
You'll notice I included while loops rather than for loops. This is because while loops are ideal when you don't know how many times you're going to need to iterate.
The while in the main method checks to see whether the user would like another game. Notice that it assumes that the user wants to play at least one game. I did this by setting wantstoplay as true before we entered the loop, but this also could've been done with a do-while loop. For more, see (http://www.java-examples.com/do-while-loop)
The while in the play method checks to see whether the user needs to make another guess because he hasn't gotten the answer yet. Just like we can't know how many times the user wants to play before hand, we can't know how many guesses the user will take either.
Hope this helps you get back into programming!
In the following code The first method (generateRandomNumber) generates a random no between 1 and 10. The second method (guessRandomNumber) then allows the user to guess the number. The problem I am having is that when the user guesses the number wrong it generates another random number instead of the inital one. As a result the user could guess and never get it correct even by entering every possible number. Can anyone advise how I would change this.
First method (generating the number):
public static int generateRandomNumber() {
Random random = new Random();
// Declaring int for random number and defaulting to 0
int randomNumber = 0;
// Assigning randomNumber between 1 and 10
randomNumber = random.nextInt(10);
randomNumber++;
return randomNumber;
}// end of generateRandomNumber
Second Method (guessing the number):
public static void guessRandomNumber() {
// declare var for user guess and default to zero
int userGuess = 0;
boolean validNumber=false;
boolean correctGuess=false;
do{
do{
try{
validNumber=true;
// Get user guess (between 1 and 10)
System.out.println("Please enter a number between 1 and 10...");
userGuess = scanner.nextInt();
}catch (Exception ex){
System.out.println("Sorry invalid entry...");
//Flush scanner
scanner.next();
validNumber=false;
}
}while (!validNumber);
if (userGuess == generateRandomNumber()) {
System.out.println("Guess correct, well done!");
correctGuess=true;
} else {
System.out.println("Sorry guess Incorrect please try again!");
correctGuess=false;
}
}while (!correctGuess);
}// end ofGuessRandomNumber
Attempt:
public static void guessRandomNumber() {
// declare var for user guess and default to zero
int userGuess = 0;
boolean validNumber=false;
boolean correctGuess=false;
int secretNumber=generateRandomNumber();
do{
do{
try{
validNumber=true;
// Get user guess (between 1 and 10)
System.out.println("Please enter a number between 1 and 10...");
userGuess = scanner.nextInt();
}catch (Exception ex){
System.out.println("Sorry invalid entry...");
//Flush scanner
scanner.next();
validNumber=false;
}
}while (!validNumber);
if (userGuess == secretNumber) {
System.out.println("Guess correct, well done!");
correctGuess=true;
} else {
System.out.println("Sorry guess Incorrect please try again!");
correctGuess=false;
}
}while (!correctGuess);
}// end ofGuessRandomNumber
You need to generate the random number first, before the user guesses, and store it in a variable. Then, instead of calling generateRandomNumber() in the line
if (userGuess == generateRandomNumber())
you need to compare it with that variable.
You should generate the random number before the first do loop. Keep it in a variable called correctNumber, then test that userGuess == correctNumber.