How to get method to recognize else part of if statement? [duplicate] - java

This question already has answers here:
How can I check for invalid input and loop until the input is valid?
(3 answers)
Closed 5 years ago.
I've made a street craps game and have an error checker in the beginning to make sure the input is valid, I put it in an if statement and then have the rest of the code (for valid inputs) as the else but it isn't recognizing the else part when the user puts in a valid number.
public void play() { //method
System.out.println("Please pick a number.");
guess = scan.nextInt();
if (guess == 7 || guess == 1 || guess == 0 || guess > 12) {
System.out.println("Sorry, that is an invalid input, please choose another number.");
guess = scan.nextInt();
} else {
int roll = dieOne.roll();
int roll2 = dieTwo.roll();
int rollSums = roll + roll2;
System.out.println(roll + "+" + roll2);
while (rollSums != 7) {
if (guess == rollSums) {
System.out.println("Congratulations, you win! Your number was rolled before a seven was rolled!");
rollSums = 7;
guess = 7;
} else {
roll = dieOne.roll();
roll2 = dieTwo.roll();
rollSums = roll + roll2;
System.out.println(roll + "+" + roll2);
}
}
if (rollSums != guess) {
System.out.println("Sorry, your number was not rolled before a seven was rolled.");
}
}
}

I guess you want to execute the if part until the if condition is not satisfied, and then you want to execute the else part. If this is what you want you need to execute the if part as a while loop, and the else part as code after the while loop.

You need a while loop to make sure you get a good input first, and then do the game logic, like this:
int guess = scan.nextInt();
while (guess == 7 || guess == 1 || guess == 0 || guess > 12){
System.out.println("Sorry, that is an invalid input, please choose another number.");
guess = scan.nextInt();
}
//Game Logic (Stuff in else section)

Related

Basic Java HiLow guessing game

I am fully aware this question has been asked many times, it is a classic first year problem in CSC. I am not looking for the solution to the problem itself. I think I have it basically done however I am missing something that I cannot find how to do.
Here is my code:
import java.util.Scanner;
import java.util.Random;
public class HiLow
{
public static void main (String[] args)
{
Random generator = new Random();
Scanner scan = new Scanner(System.in);
int num1,guess;
int count = 0;
num1 = generator.nextInt(100) + 1;
while(true) {
System.out.print("Enter an integer between 1 or 100 or enter 0 at anytime to quit: ");
guess = scan.nextInt();
count++;
if(guess == num1 || guess == 0) {
if(guess == 0) {
System.out.println("Thanks for playing");
break;
}
System.out.println("Congrats you've guessed correct and your total guesses is " + count );
break;
}
else if (guess > 100 || guess < 1) {
System.out.print("I see you cannot follow instructions. I said ");
count--;
}
else if (guess > num1) {
System.out.println("You have guessed too high. ");
}
else {
System.out.println("You have guessed too low.");
}
}
}
}
My problem is i am required to prompt the user at the point of "if the user quits or successfully guesses the correct number, prompt the user to see if they wish to play again". I am lost and not sure how to continue my while loop from the beginning after my breaks. Is there a way to end the break condition i have from (guess == num1 || guess ==0) and direct my program to start again at the while(true) statement?
Thanks
I will say search up continue;
Tips to help further:
The continue statement is used to bring the loop back to the start, try it instead of a break where you want the user to continue.
You need some sort of check if the user wants to continue, (try asking them to type in some specific int you check, p.s negative numbers are integers as well)
#Ahmed thinks you should continue, I would rather not break, or conditionally break.
Well there are multiple ways you could accomplish this, One would be to just to prompt the user with a "press q to quit" dialogue using the Scanner class where .next() returns the String when the user hits enter:
if(guess == num1 || guess == 0) {
if(guess == 0) {
System.out.println("Thanks for playing");
}else{
System.out.println("Congrats you've guessed correct and your total guesses is " + count );
}
System.out.println("would you like to play again [y/n]?");
if(scan.next().equals("y")){
num1 = generator.nextInt(100) + 1;
count=0;
}else{
break;
}
}
If thats what you mean. Hopefully I helped.
or maybe you can have it only quit at zero, if so just remove that second break and replace it with num1 = generator.nextInt(100) + 1; to set the new value to guess.

While loop not working according to the condition in Java

I am trying to build a Number guessing game which has a while loop with 2 conditions in it. However even after 1 of those 2 conditions become false then also the loop keeps going on even though I have || operator between those conditions. Also if I clear out the first condition of while loop then the second one works just perfectly as I want it to but if it is present then idk why it doesn't stop. Here is my code:
import java.util.Random;
import java.util.Scanner;
public class NumberGuess {
public static void main(String args[]) {
Random num = new Random();
int number = 1 + num.nextInt(10);
Scanner inp = new Scanner(System.in);
boolean guessed = false;
System.out.println("Welcome to Number guess!");
int guess_count = 5;
while(guessed == false || guess_count > 0 ) {
System.out.print("Enter your guess: ");
int input = inp.nextInt();
if(input == number) {
System.out.println("You guessed it right!");
guessed = true;
}
else {
System.out.println("Nope!");
guessed = false;
guess_count--;
System.out.println("Guesses left: " + guess_count);
}
}
}
}
When counter goes below 0 then also the loop keeps going on but I don't want it to.
Please tell me where am I wrong.
You don't need an OR operator. What you need is an AND operator. Means your condition should be (guessed == false && guess_count > 0 ).
WHY?
Because the OR conditional operator works if either the condition is true, in your case if the user unable to guess 5 times then your guessed variable is still false while your guess_count is less than zero, so your one condition is true. The AND operator checks for both the condition.
The condition of your while loop should be changed from an OR || to an AND &&. Currently, the || will allow execution if either guessed == false OR guess_count > 0. Only one of these conditions must be true for the while loop to continue executing.
while(guessed == false && guess_count > 0 ) {
Change to an AND && means that if the number is guessed correctly, guessed will now be true and the while loop will halt after that iteration. I was not getting any errors for when the guess_counter dropped below zero. Try it again to be sure.
Consider modifying your loop like this:
while(guess_count > 0 ) {
System.out.print("Enter your guess: ");
int input = inp.nextInt();
if(input == number) {
System.out.println("You guessed it right!");
break;
}
else {
System.out.println("Nope!");
guessed = false;
guess_count--;
System.out.println("Guesses left: " + guess_count);
}
}
OR just modify you condition like this:
while(!guessed && guess_count > 0 ) {
You can correct your code by replacing || with &&. Why use an extra flag variable when you have guess_count decrementing to check for number of guesses. The program will terminate after guessed number is equal to the input. Here is simple implementation:
while(guess_count-->0) {
System.out.print("Enter your guess: ");
int input = inp.nextInt();
if(input == number) {
System.out.println("You guessed it right!");
guessed = true;
break; // The user has already guessed the number no need to guess more
}
else
System.out.println("Nope!\nGuesses left: " + guess_count);

How to fix this random number guessing game use a do-while loop program?

Create a program that randomly generates a number from 1-100 and asks the user to guess it. If the number the user inputs is to low or to high display a message to tell them so. When the user guesses the random number tell the user how much tries it took him to get that number. After that ask the user if they want to do it again if the user does repeat the process with a new random number generated.
The problem is that I can't seem to figure out how to let the user do it again, it seems to display an error in code when I run the program. If anyone can help me with this issue that would be great. Thank you!
import java.util.Scanner;
import java.util.Random;
public class RandomGuess
{
public static void main(String [] args)
{
Scanner keyboard = new Scanner(System.in);
Random randy = new Random();
//#declaring variables
int num, count = 0;
final int random = randy.nextInt(100);
String input;
char yn;
//#random number
System.out.println("Num = " + random);
//#title or header
System.out.println("Random Number Guessing Game");
System.out.println("===========================");
//#asking user for input
do
{
System.out.print("Guess the random number " +
"from 1 to 100===> ");
num = keyboard.nextInt();
//#if the number the user entered
//#was less than the random number
if(num < random)
{
//#display this message
System.out.println("Your guess is too low try again...");
System.out.println();
}
//#if the number the user entered
//#was less than the random number
if(num > random)
{
//#display this message
System.out.println("Your guess is too high try again...");
System.out.println();
}
count++;
if (num == random)
{
System.out.println("You guessed the random number in " +
count + " guesses!");
break;
}
do
{
System.out.print("Continue? (Y or N)==> ");
input = keyboard.nextLine();
yn = input.charAt(0);
}
while(yn == 'Y' || yn == 'y');
}
while (num > 1 || num > 100);
}
}
There are a couple of problems with your code without even seeing the error that is displayed (I've put comments in those areas):
count++;
if (num == random)
{
System.out.println("You guessed the random number in " +
count + " guesses!");
break;
} // You should put an else here
do
{
System.out.print("Continue? (Y or N)==> ");
input = keyboard.nextLine();
yn = input.charAt(0);
}
while(yn == 'Y' || yn == 'y'); // This will keep asking if you want to try again so long as you enter a "y"
// But it won't actually let you try.
// Why? Because if you enter a y" it will loop back to the question.
}
while (num > 1 || num > 100); // This should probably be (random != num)
}
}
Here is a revised version
count++;
if (num == random) {
System.out.println("You guessed the random number in " +
count + " guesses!");
} else {
yn = 'x'; // can be anything other than y or n
while(yn != 'y' && yn != 'n') {
System.out.print("Continue? (Y or N)==> ");
input = keyboard.nextLine();
yn = input.toLowerCase().charAt(0);
}
}
}
while (num != random && yn == 'y');
}
}
Hopefully this is enough to move you forward.
Also, please post the error message and/or a description of what it is doing wrong along with a description as to what you actually wnt it to do.
As for the exception, the problem is that scanner.nextInt does not consume the newline at the end of the numbe you entered. So, your "continue Y/N" question gets what's left over from the previous line (i.e. a new line => an empty string).
You could try this:
num = -1; // Initialise the number to enable the loop
while (num <= 1 || num >= 100) {
System.out.print("Guess the random number from 1 to 100===> ");
String ans = keyboard.nextline();
try {
num = Integer.parseInt(); // Convert the string to an integer - if possible
} catch (NumberFormatException e) {
// If the user's input can not be converted to an integer, we will end up here and display an error message.
System.out.println ("Please enter an integer");
}
}

do while loop syntax error, program not going through all of code, code efficiecy [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 3 years ago.
I made a basic number guessing game, everything was working fine until i tried to add a "play again" feature at the end of it. When the program is run, after inputting the first guess, it just starts the loop over again without going through the rest of it. Also, I am unsure if my code is efficient or not. It seems like too much coding for a simple concept. Is this an average length for a basic guessing program? Sorry if my questions are worded strangely. I'm a first year college student just learning the basics of programming. Here is my code:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random randomNum = new Random();
boolean playing = true;
do {
int max = 100;
int min = 1;
int counter = 10;
int guess = 0;
int guessThis = min + randomNum.nextInt(max);
System.out.println("I'm thinking of a number between 1 and 100. You have 10 tries to guess it. What's your first guess?");
guess = input.nextInt();
counter--;
if (guess == guessThis) {
playing = false;
} else {
playing = true;
}
if (guess > max) {
System.out.println("I said the number is between 1 and 100. You think this is a GAME MUTHA FUCKA??! Guess again... :) " + counter + " guesses left.");
}
if (min > guess) {
System.out.println("Bruh. Are you stupid? " + guess + " is not between 1 and 100. Try again dummy boi. " + counter + " guesses left.");
}
if (guess > guessThis && min <= guess && guess >= max && playing == true && counter > 0) {
System.out.println("Too high. Guess again. " + counter + " guesses left.");
} else if (guess < guessThis && min <= guess && guess >= max && playing == true && counter >0) {
System.out.println("Too low. Guess again. " + counter + " guesses left.");
}
if (playing == false && counter > 0) {
System.out.println("You guessed it!");
}
if (counter <= 0) {
System.out.println("You lose! Ha! Fuck off broooooo. My number was " + guessThis);
playing = false;
}
}while (playing == true);
String answer;
if (playing == false) {
System.out.println("Wanna play again? (y/n)");
}
answer = input.next();
if (answer == "n") {
System.out.println("My game isn't fun enough for you? Wow, okay, rude. Bye then. Dh.");
input.close();
} if (answer == "y") {
playing = true;
}
}
}
use
}while (playing == true);
after the end of if statement
if (answer == "y") {
playing = true;
}

Last questions: Mastermind Java program

I have two questions regarding my code.
Why does is the output "Oops please enter a number between 1 and 6" when I enter a number between 1 and 6. When I try to be more specific and make an else if statement, nothing happens when I enter a number NOT between 1 and 6.
How do I restart my program? In my code, there is an if statement
when the user inputs "play again" My commented out line reads
Mastermind.main() to re run the program, but that didn't work.
Here is the code:
import java.util.Scanner;
public class Mastermind {
public static void main (String [] args) {
// boolean variable to signal when the game is over.
boolean done = false;
// Scanner object
Scanner scanner = new Scanner(System.in);
// sets the value to twelve outside the loop so it doesn't set back each time.
int guesses = 12;
System.out.println("Please enter a number between 1-6 to begin (or \"quit\") to exit.");
// while loop for the game
while (!done) {
//System.out.println("Please enter a number between 1-6 (or \"quit\") to exit the game:");
// user input
String input = scanner.nextLine();
int number = 0; //Just initialized to some number
// checks to see if the user wants to quit the game.
if (input.equalsIgnoreCase("quit")) {
System.out.println("Goodbye!");
done = true;
scanner.close();
}
else{
try{
//Trying to see if the input was a number
number = Integer.parseInt(input);
}
catch(Exception e){
//The input wasn't an integer, it's invalid the starts loop again.
System.out.println("Invalid input.");
continue;
}
}
// defines necessary int variables
int random1 = (int) (Math.random() * 7);
int random2 = (int) (Math.random() * 7);
int random3 = (int) (Math.random() * 7);
int random4 = (int) (Math.random() * 7);
// If the user doesn't and decides to play, it runs this code.
// checks to see if the user enters a number between 1-6
if (number >= 1 && number <= 6) {
if (number == random1) {
System.out.println("You guessed a correct number!");
guesses--;
System.out.println("guesses = " + guesses);
}
else if (number == random2) {
System.out.println("You guessed a correct number!");
guesses--;
System.out.println("guesses = " + guesses);
}
else if (number == random3) {
System.out.println("You guessed a correct number!");
guesses--;
System.out.println("guesses = " + guesses);
}
else if (number == random4) {
System.out.println("You guessed a correct number!");
guesses--;
System.out.println("guesses = " + guesses);
}
else {
System.out.println("Sorry that's not one of the numbers! Try again.");
guesses--;
System.out.println("guesses = " + guesses);
}
}
if (guesses == 0){
System.out.println("You've run out of guesses. To play again, enter \"play again\". Otherwise, enter or \"quit\")");
if (input.equalsIgnoreCase("play again")){
// how do I restart the program?
//Mastermind.main(); // QUESTION 2
}
else if (input.equalsIgnoreCase("quit")){
System.out.println("Goodbye!");
done = true;
scanner.close();
}
else {
System.out.println("Goodbye!");
done = true;
scanner.close();
}
}
else { //QUESTION 1
System.out.println("Oops! Please choose a number between 1 and 6");
}
}
}
}
You're printing that message every time through the loop whenever guesses == 0 evaluates to false. You probably just need to switch the order of the two blocks. Instead of this:
if (number >= 1 && number <= 6) {
...
}
if (guesses == 0) {
...
}
else { //QUESTION 1
System.out.println("Oops! Please choose a number between 1 and 6");
}
Use this:
if (number >= 1 && number <= 6) {
...
}
else { //QUESTION 1
System.out.println("Oops! Please choose a number between 1 and 6");
}
if (guesses == 0) {
...
}
Regarding restarting your program: if I'm reading the logic correctly, all you need to do is keep done set to false and reset guesses to 12.
Two other logic points. First, you should probably either continue or break after detecting that the user has entered "quit". Second, it seems like you are generating four new random integers for every user guess. I don't know if that's what you intended, but you might want to change the logic a bit. That might also affect the restart logic.

Categories

Resources