Will not stop looping - java

Write a program that generates a random number (between 1 and 10) and asks the user to guess what the number is. If the user’s guess is higher than the random number, the program should display “Too high, try again.” If the user’s guess is lower than the random number, the program should display “Too low, try again.” The program should use a loop that repeats until the user correctly guesses the random number.
This is my code and when I run it, it will not stop looping and I have no idea why. Thank you!!
/////guess/////
import java.util.Random;
import java.util.Scanner;
public class guess
{
public static void main (String [] args)
{
Random rand = new Random();
int numberToGuess =rand.nextInt(10);
Scanner input=new Scanner(System.in);
int guess;
boolean win =false;
while (win == false)
System.out.println("Guess a number between 1 and 10");
guess = input.nextInt();
{
if(guess == numberToGuess)
win=true;
}
if(guess<numberToGuess)
{
System.out.println("Your guess is too low");
}
{
if (guess > numberToGuess)
System.out.println("Your guess is too high");
System.out.println("You win!");
System.out.println("The number was" +numberToGuess);
}
}
}

This doesn't just apply to while statements; if and for statements are affected by this as well.
Your while statement will only ever execute the next line if it is not contained in a block.
// Without curly braces, the println is the only thing in the loop.
while (win == false)
System.out.println("Guess a number between 1 and 10");
// This isn't part of the loop!
guess = input.nextInt();
You fix this by ensuring that everything you want to loop on is contained by curly braces:
while(!win) {
// ALL of the logic you want to execute while win is false
}

Provided you have copied your code as is, have a look at your while loop you have no {} so it will keep printing
System.out.println("Guess a number between 1 and 10");
until win changes, which in this code it won't.

Related

How do I make it so that it stars over if the user inputs wrong number OR start over if user types in "1"

package w3school;
import java.util.Random;
import java.util.Scanner;
public class nyttprogram {
static void indata() {
{
Scanner determinedNumber = new Scanner(System.in);
int user, computer, number, user2;
System.out.println("Input a number from 0-10");
user = determinedNumber.nextInt();
Random random = new Random();
int randomInt = random.nextInt(10);
if (user == randomInt) {
System.out.println("You guessed the correct number!");
} else {
System.out.println("You guessed the wrong number");
System.out.println("The correct number was: " + randomInt);
}
System.out.println("Input 1 if you want to try again: ");
}
}
public static void main(String[] args) {
indata();
}
}
How do I make the class start over when user input 1 OR if the Class can start over if User inputs wrong number from the start, many thanks
How do I make the class start over when user input 1 OR if the Class can start over if User inputs wrong number from the start, many thanks
The "start over" logic based on some conditions is usually implemented with while and do/while loops.
First let's extract those conditions. We want to iterate again (start over) if:
The user's guess is wrong.
The user's guess is correct, but they input a number different than 1 when asked if they want to continue.
Since we want to run the program at least once, the natural approach would be with a do/while. This will run one iteration, then check against the conditions wanted.
Here's what it looks like:
private static void inData() {
Scanner userInputScanner = new Scanner(System.in);
Random random = new Random();
// Declare the stop/continue condition
boolean isLoopContinue;
do {
// Generate a random number
int expectedNumber = random.nextInt(10);
// Ask the user to guess a number
System.out.println("Input a number from 0-10");
int givenNumber = userInputScanner.nextInt();
if (givenNumber == expectedNumber) {
// Correct answer, check if the user wants to continue
System.out.println("You guessed the correct number!");
System.out.println("\nInput 1 if you want to try again: ");
// If they input "1", then we continue. Else we stop
isLoopContinue = userInputScanner.nextInt() == 1;
} else {
// Wrong answer, loop again
System.out.println("You guessed the wrong number");
System.out.println("The correct number was: " + expectedNumber);
isLoopContinue = true;
}
} while (isLoopContinue);
}

Random number generator within loop

trying to create a Random number generator within a while loop that controls the Number Guessing Game. The issue is the "too high" and "too low" hints will say one number (ex:35) is too low, but then say the nest input number (ex:36) is too high. Then when I move the call a random function in the nested while loop, it generates the same random number each time.
I have tried moving the call to random function to my most inner loop, but then it generates the same random number. Currently, it is in the outer while loop, but then the issue of the high/lows occurs
import java.util.Scanner;
import java.util.Random;
public class numberGuessingGame
{
public static void main (String[] args)
{
int randomNumber, userNumber = 0, guesses = 0, correct;
final int MAX = 100;
char playAgain, playGame = 'y';
//ask user if they wish to play
System.out.println("Would you like to play the Number Guessing Game? y / n");
Scanner scan = new Scanner (System.in);
playGame = scan.next().charAt(0);
Random generator = new Random();
//while loop to continue to exacute game as long as user enters 'y'
while (playGame == 'y'){
if (playGame != 'y')
break;
randomNumber = generator.nextInt(MAX) + 1;
//flag
correct = 0;
//loop to control the round
while (correct == 0) {
//get user number
System.out.println("Please pick a number between 1 and 100.");
userNumber = scan.nextInt();
//high and low sugguestion
if (userNumber > randomNumber)
System.out.println("Number is too high, try something lower.");
if (userNumber < randomNumber)
System.out.println("Number is too low, try something higher.");
if (userNumber == randomNumber){
System.out.println("That number is correct!");
System.out.println("Would you like to play again? y/n");
playGame = scan.next().charAt(0);
}
guesses++;
System.out.println("You have guessed " + guesses + " times!");
}
}
//break statement skips here when 'n' is entered in
// the game prompting question
System.out.println("Thanks for playing, have a nice day!");
}
}
I'd like to suggest some changes you might consider:
use a boolean for correct rather than an int
remove your if statement immediately after the while: it is redundant
use do-while when the loop must be executed at least once
use Integer.compareTo rather than separate comparisons
Your inner loop does not terminate that's why you have the same
randomNumber, change correct=0 value to terminate the inner while loop
if (userNumber == randomNumber){
System.out.println("That number is correct!");
System.out.println("Would you like to play again? y/n");
playGame = scan.next().charAt(0);
correct=1; //Just to remove correct=0 value
}

"Guess the number" in Java

We are meant to to create a program in java in which the computer randomly guesses a number between 1-100 and allows the user to guess to the number. If the number is lower than the random number the program should say: lower! and of higher, the program should say: higher! If the user guesses the right number it should say congratulations you guessed the right number in X amount of tries, This is what I have so far, when I execute in cmd it just spams either higher or lower and I need help working it out.
import java.util.Scanner;
import java.util.Random;
public class GuessingGame{
public static void main(String[] args) {
int random, guess, attempts;
Scanner keyboard = new Scanner(System.in);
Random generator = new Random();
random = generator.nextInt(100) + 1;
attempts = 1;
System.out.print("I am thinking of a number between 0 and 100, what do you think it is?");
guess = keyboard.nextInt();
while (guess != random) {
if (guess > random) {
System.out.print("Lower!");
attempts += 1;
}
else {
System.out.print("Higher!");
attempts +=1;
}
}
System.out.print(random + "is the correct answer and it took you" + attempts + "attempts to guess it!");
}
}
You're only reading the input once and then looping on it forever (you read the input outside the loop).
Try reading the input inside the loop and using do-while loop:
guess = 0;
do {
guess = keyboard.nextInt();
if (guess > random) {
System.out.print("Lower!");
attempts += 1;
} else {
System.out.print("Higher!");
attempts +=1;
}
} while (guess != random);
Place the guess = keyboard.nextInt(); into the while loop to ask again and again.
You only take a single guess and stuck yourself in the while loop, it's like if the number randomized by the program is 70, and for example if the user gave his first attempt as 50, the code will enter the while loop as the number is not 70, but it won't come out as you coded while(guess != random) and guess will ever equal random in our case, and it will be always lower for an infinite time because you give him the ability to enter a single attempt and then you enter an endless while loop without giving him the ability to change his attempt through it, So, you must allow him to has his second, third, ..etc attempts inside the while loop itself, like the following:
guess = keyboard.nextInt();
while (guess != random) {
if (guess > random) {
System.out.print("Lower!");
attempts += 1;
}
else {
System.out.print("Higher!");
attempts +=1;
}
guess = keyboard.nextInt();
}
The random number generate the number once the we will call the method isNumCorrect again using while loop until it returns true and the guess count will increase every time the number pass through isNumCorrect
import java.util.Random;
import java.util.Scanner;
class guessGame {
int guessedNumber;
int userNumber;
int guess_count;
public guessGame() {
Random rand = new Random();
guessedNumber = rand.nextInt(100);
}
void userNum() {
System.out.println("GUESS THE NUMBER");
Scanner sc = new Scanner(System.in);
userNumber = sc.nextInt();
}
boolean isNumCorrect() {
guess_count++;
if (userNumber == guessedNumber) {
System.out.printf("yes you guessed it right in %d guesses", guess_count);
return true;
} else if (userNumber < guessedNumber) {
System.out.println("too low");
} else {
System.out.println("too high");
}
return false;
}
}
public class cwh_42_guess_the_number {
public static void main(String[] args) {
guessGame g = new guessGame();
boolean b = false;
while (!b) {
g.userNum();
b = g.isNumCorrect();
}
}
}

Enter an integer, program displays whether odd/even, -1 to terminate

so i need to write a Java application which allows the user to enter an integer value and the application then calls a method called isEven to determine and display whether the value entered is either odd or even. The application should stay running until -1 is entered.
I have managed to do this much but I have ran into a problem
import java.util.Scanner;
public class Enter_Input {
//create method isEven
private static void isEven(int[] numbers) {
System.out.println( );
}
static int number = 0;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter number (-1 to quit): ");
number = input.nextInt();
while(number > 0) {
if (number % 2 == 0) {
System.out.println(number + " is even");
}//end if statement
else {
System.out.println(number + " is odd");
}//end else statement
if (number == -1){
System.out.println("Program Terminated");
break;
}//end if statement
}//end while loop
}//end main method
}//end class
when i enter a number this is what happens
Enter Number (-1 to quit):
2
2 is even
2 is even
2 is even
2 is even
2 is even
etc
i want it to look like
Enter Number (-1 to quit):
2
2 is even
Enter Number (-1 to quit):
7
7 is odd
Enter Number (-1 to quit):
-1
Program Terminated
how do i go about fixing this
and also how do i use the method isEven in the code, i'm only learning how to use java so could someone please guide me in the right direction with this
Here you go! I have used a do-while loop for you to understand the use of that too. You should be easily able to switch it to a while loop if you prefer. Please try and understand the logic here, so you can reproduce it in the future. Assuming you are using Java to learn object-oriented programming, you may want to remove the static keyword from your isEven() method and understand the effect it has.
I know you're still learning, but as Mike mentioned, avoid getting into the habit of commenting the way you are here. Write meaningful comments to explain a more high-level view of what you are trying to achieve. (Business value, if you will). Not trying to criticize here, I just hope you find the comments useful :-) Cheers
import java.util.Scanner;
public class Enter_Input {
//create method isEven
private static void isEven(int currentNumber) {
if (currentNumber % 2 == 0) {
System.out.println(currentNumber + " is even\n");
}//end if statement
else {
System.out.println(currentNumber + " is odd\n");
}//
}
public static void main(String[] args) {
int number = 0;
Scanner input = new Scanner(System.in);
do {
System.out.println("Enter number (-1 to quit): ");
number = input.nextInt();
if (number == -1) {
break;
}//end if statement
else {
Enter_Input.isEven(number);
}//end else statement
} while (number > 0); //end do while loop
System.out.println("Program Terminated");
}//end main method
}//end class

Infinite pre-test while loop (java)

I am trying to create a guessing game program. The user enters a number and is told if the number is too high or low, then is told to guess again. I made an infinite loop and i cannot figure out how to change it. I realize that if the guess is wrong, then the program will keep checking the wrong value and printing a "wrong number" message.
package guessinggame;
import java.util.Scanner;
/**
*
* #author
*/
public class GuessingGame {
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
Scanner input = new Scanner (System.in);
int guesses; //number of users guesses
int housePick; //number the user must guess
int guess; //users guess
housePick = (int)((Math.random() * 100) +1 );
//sets housePick to random number from 1 to 100
System.out.println("I'm thinking of a number between 1 and 100") ;
//print "Im thinking of a nubmer between 1 and 100"
System.out.println("Can you guess what it is?");
//print "can you guess what it is"
System.out.println
("Enter a number from 1 to 100 (including 1 and 100)");
//prompt user to enter number
guess = input.nextInt();
//save entered number as guess
while (guess != housePick) //while guess doesnt = housePick...
{
if (guess > housePick) //and if guess > housePick...
{
if ((guess - 10) <= housePick )
//and if guess is 10 numbers away from housePick...
{
System.out.println("Close, but too high. Try again.");
//print "close but too high, try again"
}
else //if guess is not close and guess>housePick...
{
System.out.println ("Too high, try again.");
//then print "Too high, Try again"
}
}
else //If guess<housePick
{
if ((guess + 10) >= housePick) //AND if guess is close to housePick
{
System.out.println ("close, but too low.") ;
//then print "close, but too low"
}
else//If guess isnt close to housePick and is less than housePick...
{
System.out.println ("Too low.");//then print "too low"
}
}
}
System.out.println ("You win! It took you " + "guesses.");
//If guess = housePick print "Yout win! It took you (# of guesses)"
}
}
You never get a user selection and change the guess variable's value from within the while loop. If guess is never changed, the loop will never end since this never changes: while (guess != housePick) and the condition remains false.
Solution:
Do the obvious: use your input Scanner variable to get user input from inside the while loop, and use it to re-set guess to a new value.
You are correct up to some level but when the things go wrong you have to get the input from the user before the loop ends. So you have to get the input from the player just before the while loop ends.I have done the correction and The updated code (only the while loop part) as follows
while (guess != housePick) //while guess doesnt = housePick...
{
if (guess > housePick) //and if guess > housePick...
{
if ((guess - 10) <= housePick )
//and if guess is 10 numbers away from housePick...
{
System.out.println("Close, but too high. Try again.");
//print "close but too high, try again"
}
else //if guess is not close and guess>housePick...
{
System.out.println ("Too high, try again.");
//then print "Too high, Try again"
}
}
else //If guess<housePick
{
if ((guess + 10) >= housePick) //AND if guess is close to housePick
{
System.out.println ("close, but too low.") ;
//then print "close, but too low"
}
else//If guess isnt close to housePick and is less than housePick...
{
System.out.println ("Too low.");//then print "too low"
}
}
/// this is the correction
System.out.println
("Enter a number from 1 to 100 again (including 1 and 100)");
//prompt user to enter number
guess = input.nextInt();
}
Add below line just before the while loop ends so that it will ask every time when the guess is wrong and successfully exit from the loop when guess is right.
while (guess != housePick) //while guess doesnt = housePick...
{
if (guess > housePick)
{
\\Your code remains as it is.
...
...
...
...
} //if-else loop ends here.
guess = input.nextInt();
}//while ends here.
As mentioned by others, the reason you are having issues stems from the fact that you are not looping input, only checking. Putting your input.nextInt() into the while loop will solve this issue.
Also, as a point of procedure, this is the appropriate location to use a do/while loop rather than a normal while (as you always want to run the input at least once).

Categories

Resources