Java while loop not working with input checking of characters - java

The code below is from a game in which I need to generate 2 random numbers in java, and the user is presented with one of them. They then have to guess if the second number is higher or lower than the first. I created a while loop to check for errors in their input and the loop is executed even if the condition is not true. Entering H means their guess is the next number is higher, and L means they believe its lower
// Input
System.out.println ("Do you think the second number is higher or lower (enter 'H' or 'L' respectively): ");
char userGuess = Character.toUpperCase(input.next().charAt(0));
// Input error check (and immediate output of second number)
while (userGuess != 'H' || userGuess != 'L') {
System.out.println ("Sorry, I didn't understand that. Please try again: ");
userGuess = Character.toUpperCase(input.next().charAt(0));
}
System.out.println ("The second number was " + secondRandomNumber);

Use && not ||. Of course it's not going to be H or not going to be L
while (userGuess != 'H' && userGuess != 'L') {
System.out.println ("Sorry, I didn't understand that. Please try again: ");
userGuess = Character.toUpperCase(input.next().charAt(0));
}

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);

Having difficulty ignoring case sensitivity for do while loop

Trying to let the user exit the program using the letter 'N' or 'n' but it will only let them exit when using 'N'
Below is my code, any help is appreciated!!
System.out.print(" Do you want to repeat the ");
System.out.println("program ['Y' or 'N']");
Choice = sc.next().charAt(0);
} while (Choice != 'N' || Choice != 'n');
}
}
You have to use while (Choice != 'N' && Choice != 'n'); .
It must be AND condition. Not an OR condition.
You are using the wrong operator:
while (Choice != 'N' && Choice != 'n');
Right now, your code states that the loop will continue when the character is either not 'N' or not 'n'. Since the character can't be 'N' and 'n' at the same time, the loop will always continue. Switching the operator to a && requires that the character is neither N nor n to continue.

Else in loop not working when an invalid number is entered

System.out.println("Enter number of dice to throw, an integer [2, 10]: ");
Scanner keyboard = new Scanner (System.in);
n = keyboard.nextInt();
//if the input is valid
if (n>1 && n<11)
{`
System.out.println("good");
Random rn = new Random();
int random = rn.nextInt((6-1) +1) +1;
System.out.println("random number is " + random);
}
else
{
//if the users input is invalid
while (n<2 && n>10)
{
System.out.println("error, must be in [2,10] ");
n = keyboard.nextInt();
}
}
Your logic is incorrect. The number n can't be less than 2 and greater than 10 ever. You want less than 2 or greater then 10. Use || instead of &&.
while (n<2 || n>10)
If the condition in the "if" statement is not met, then wouldn't the program by default go to the 'else' statement? So would you even need the while statement?
Actually it does enter the ‘else’ but not inside the ‘while’. Because n cant be < 2 AND > 10 at the same time.
Replace
while (n<2 && n>10)
With
while (n<2 || n>10)

Why won't my Java code work? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I know this code is terribly written (first day of Java and programming), but I am writing a code in Java that will take an input from the user (the dice) and produce a random number from that dice. I have added a while loop to ask if the user would like to restart the program, but everytime I run it it tells me that it is an invalid input before I have inputted anything. Please help.
import java.util.Scanner;
import java.util.Random;
public class Java {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
String restartChoice = "y";
while (restartChoice == "y" || restartChoice == "Y"){
int choice;
System.out.println("Please choose which dice you would like to roll. 4/6/12 ");
choice = input.nextInt();
while (choice != 4 && choice != 6 && choice != 12){
System.out.println("That is not a valid input, please try again... ");
choice = input.nextInt();
}
Random rand = new Random();
int value = rand.nextInt(choice) + 1;
System.out.print("You chose to roll the ");
System.out.print(choice);
System.out.print(" sided dice. The number is ");
System.out.println(value);
System.out.println("Would you like to restart? Y/N ");
restartChoice = input.nextLine();
while (restartChoice != "y" && restartChoice != "n" && restartChoice != "y" && restartChoice != "n"){
System.out.println("That is not a valid input. Please try again. ");
restartChoice = input.nextLine();
}
}
}
}
Scanner#nextInt() does not consume newline characters resulting in the character being passed through to the loop
while (restartChoice != "y" && restartChoice != "n" && restartChoice != "y" && restartChoice != "n"){
System.out.println("That is not a valid input. Please try again. ");
restartChoice = input.nextLine();
}
Add a nextLine statement after every nextLine statement to consume this newline character.
choice = input.nextInt();
input.nextLine();
Also the == operator compares Object references. Use String#equals:
while (restartChoice.equals("y") || restartChoice.equals("Y")) {
to protect against NullPointerException you can place the String literal first. Also equalsIgnoreCase can be used to give a shorter if statement expression:
while ("y".equalsIgnoreCase(restartChoice)) {
This change is required in for while statement expression.
Use String.equals(otherString)
Strings are objects, not primitives. You are currently comparing the addresses of your strings.

Categories

Resources