Infinite pre-test while loop (java) - 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).

Related

Java High-Low Guessing Game Looping Errors

I've just started learning programming for the first time and I am working through Java to start. I am doing a common coding exercise of programming a guessing game using loops and conditionals. My program is required to do the following:
Pick a random number between 1 and 100
Repeatedly prompt the user to guess the number
Report to the user that he or she is correct or that the guess is high
or low after each guess
Offer the user the option to quit mid-game
Count the number of guesses in a game and report the number upon a correct guess
Ask the user if they want to play again upon a successful game
I have been a little bit shaky with loop syntax so far and need some help with my program because there are a lot of issues I don't know how to fix. Would anyone be kind enough to lend me a hand? Please forgive the many probably obvious mistakes.
import java.util.Scanner;
import java.util.Random;
public class Guess
{
public static void main (String[] args)
{
final int MAX = 100;
int answer, guess = 0, count = 0;
String another = "y";
Random generator = new Random();
answer = generator.nextInt(MAX) + 1;
Scanner scan = new Scanner(System.in);
System.out.println("I'm thinking of a number between 1 and " + MAX
+ ". Guess what it is: ");
guess = scan.nextInt();
while (another.equalsIgnoreCase("y"))
{
while (guess != answer)
{
while (guess > MAX || guess < 1)
{
System.out.println("Invalid input. Please re-enter a number"
+ " between 1 and " + MAX + ":");
guess = scan.nextInt();
}
if (guess == answer)
{
count++;
System.out.println("You guessed correctly!");
}
else if (guess > answer)
{
count++;
System.out.println("You guessed too high. Guess again? Y/N:");
another = scan.nextLine();
}
else if (guess < answer)
{
count++;
System.out.println("You guessed too low. Guess again? Y/N:");
another = scan.nextLine();
}
}
}
System.out.println("It took you " + count + "guess(es) to win.");
System.out.println("Do you wish to play again? Y/N:?");
another = scan.nextLine();
count = 0;
answer = generator.nextInt(MAX) + 1;
}
}
One problem is that you're not letting the user quit midway through the game because even if the user guesses a number within the 1 to 100 range and doesn't get the right answer, his or her answer to Guess again: Y/N: won't be checked since the current loop it is in only compares guess to answer, never another. Therefore, you'll end up being in an infinite loop in this case because if the user guesses 57 when the answer is 50, you'll just continuously prompt the user if he or she wants to guess again.
My recommendation would be to remove the second while loop
while (guess != answer)
{
//other stuff
}
and place the code inside that loop into the outside while loop
while(another.equalsIgnoreCase("y")){
//other stuff
}
And if you want the user to be able to play again, I would recommend putting this snippet of code you had earlier inside the if statement where you check if the user has guessed correctly,
if (guess == answer)
{
count++;
System.out.println("You guessed correctly!");
System.out.println("It took you " + count + "guess(es) to win.");
System.out.println("Do you wish to play again? Y/N:?");
another = scan.nextLine();
count = 0;
answer = generator.nextInt(MAX) + 1;
}
This way, if the user wins the game, their choice to play again will be checked in the while loop. One last thing I would recommend is moving this line
guess = scan.nextInt();
inside the while loop that checks another so that if the user wants to play again, the game will prompt the user for a guess.

java if statement not executing

I am relatively new to java and this is my first time working with if else statements. I was attempting to make a basic game in which the user guesses a number between 1-3, and the program tells them if they are right or wrong. However, when I go to execute the program, when I type 1, the program does not respond and I have to use ctrl-E to end it. What am I doing wrong? When I enter values aside from 1, the program executes as I want it to by printing "Goodbye."
Here is my code:
import java.util.*;
public class GuessTheNumber {
public static void main(String[] args) {
Scanner game = new Scanner(System.in);
Random rand = new Random();
System.out.println("Hey there! Want to play a game?");
System.out.println("\tIf yes, type 1");
System.out.println("\tIf no, type 2");
int ans1 = game.nextInt();
if (ans1 == 1) { // This is true, yet when I type 1, nothing happens.
int randomNum = rand.nextInt((3 - 1) + 1) + 1;
int guess = game.nextInt();
System.out.println("Great! I am thinking of an integer between 1 and 3. Guess what it is?");
if (guess == randomNum) {
System.out.println("Congradulations! You guessed correctly! The number was" + randomNum);
} else {
System.out.println("Sorry, your guess was incorrect. The number I was thinking of was" + randomNum);
}
} else {
System.out.println("Goodbye.");
}
}
}
This is my first time posting here, so I apologize if this question has been answered elsewhere.
Because if ans1=1, then it expects another input from user and checks if the guess and another input are same.
This is second input that it is waiting for
int guess = game.nextInt();
Input any number ,if the random number generated is equal to the number you added second time, it will return "Congradulations! You guessed correctly! The number was" else "Sorry, your guess was incorrect. The number I was thinking of was" with number
Instead of:
int guess = game.nextInt();
System.out.println( "Great! I am thinking of an integer between 1 and 3. Guess what it is?" );
You should have them reversed.
System.out.println( "Great! I am thinking of an integer between 1 and 3. Guess what it is?" );
int guess = game.nextInt();

Java Looping issue in Hangman program(Cant find)

I have the majority of my program finished, but now that I have most of the code it is tough to find the errors. I have multiple errors at the moment, but the main error I really need help with is that my program will loop the same guess over & over if it is correct. It is in an infinite loop, & I cannot find where it is. This has also brought to my attention that my program will go into negative guesses as it is supposed to end when it gets to 0. Some other errors that would be nice to get help with is 1) it shows a correct guess as an incorrect guess 2) it can only replace one letter in the secret word if there are multiple it will give me an error & end the program. & 3) if I enter 9 to quit, it does not quit.
Thanks in advance for any help. I can add code if needed ( I am only posting the main body ATM.)
public static final int DICTIONARY = 15000;
public static final int GUESSES = 8;
public static final int SECRETLENGTH = 20;
public static void main(String[] args) {
int usedSize = 0, randomWord, guesses = GUESSES;
String word, secretWord, guess, incorrectGuess, correctWord, playAgain;
char letter;
try
{
// Set up connection to the input file
Scanner hangmanDictionary = new Scanner(new FileReader("dictionary.txt"));
String [] dictionary = new String [DICTIONARY];
while (usedSize < DICTIONARY && hangmanDictionary.hasNextLine()) {
dictionary[usedSize] = hangmanDictionary.nextLine();
usedSize++;
}
kbd.nextLine();
clearScreen();
randomWord = pickRandom(DICTIONARY);
word = dictionary[randomWord];
secretWord = secret(word);
//comment out when done testing
System.out.println(word);
System.out.println("Here is the word to guess: " + secretWord);
System.out.println("Enter a letter to guess, or 9 to quit.");
guess = kbd.next();
do {
while (!guess.equals("9") || !(guess.equals(word) && guesses > 0)) {
letter = guess.charAt(0);
incorrectGuess = "";
incorrectGuess += letter;
if (word.indexOf(letter) < 0) {
guesses--;
System.out.println("Incorrect guesses: " + incorrectGuess);
System.out.println("Number of guesses left: " + guesses);
System.out.println("Enter a letter to guess, or 9 to quit.");
guess = kbd.next();
}
else {
//FINSH THIS
correctWord = correctWord(guess, word, secretWord, letter);
System.out.println(correctWord);
System.out.println("Incorrect guesses: " + incorrectGuess);
System.out.println("Number of guesses left: " + guesses);
System.out.println("Enter a letter to guess, or 9 to quit.");
guesses--;
}
}
if (guess.equals("9")) {
System.out.println("Thanks for playing!");
System.exit(0);
}
if (guess.equals(word)) {
System.out.println("You won!");
}
if (guesses == 0) {
System.out.println("You are out of guesses.");
}
System.out.println("Play again? Y/N");
playAgain = kbd.nextLine().toUpperCase();
} while (playAgain.equals("Y"));
}
catch (FileNotFoundException e) {
System.out.println("There was an error opening one of the files.");
}
}
Here's my guess:
Did you forget to put guess = kbd.next(); if the user guessed a correct character?
The inner while loop is your main problem, i.e. think about what happens when you enter a valid letter (guess), in that case the first condition of the while loop OR condition is TRUE (assuming you don't have a 9 in your secret word), so the while loop is entered without entering the second part of the OR condition. After that you enter the else part of the IF statement (since it's a valid guess) but in the else part you're not asking for the next guess, so it returns to the start of the while loop with the same guess and hence infinite loop.
Similarly, if you enter 9 to exit !guess.equals("9") evaluates to FALSE, so the second part of the OR condition is entered, in the second part
!(guess.equals(word) && guesses > 0) evaluates to TRUE (unless the secret word contains a 9) so you enter the WHILE loop which is invalid. etc ...
Try to write small parts of the code using known parameters and then bring it all together, that way it'll be easier to construct and follow the logic.

Will not stop looping

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.

Finding the Average from a list of numbers in Java

This is my first attempt at java problem I have been given as part of my Programming assignment.
I must make a program which calculates the average of a list of numbers that a user enters. the data enty should be terminated when 0 is entered. my problem is with this "ALL NEGATIVE NUMBERS SHOULD BE IGNORED"
for some reason the following code does not work, when I enter a negative number it should be ignored but for some reason it terminates the data enty
import java.util.*;
class Task_8
{
public static void main()
{
Scanner inputLine = new Scanner(System.in);
float row, numberentered, numbersum = 0, negativenumber = 0;
double result, count = 0;
System.out.println ("Welcome to Task 8 of 10 of my Programming Assignment... Nearly There!");
System.out.println ("_____________________________________________________________________");
System.out.println ();
System.out.println ("Enter as many numbers as you like and this program will tell you the arithmatic mean");
System.out.println ("Terminate data entry by entering 0");
do{
System.out.print ("Please enter a number: ");
numberentered = inputLine.nextInt();
count++;
if (numberentered < 0)
{
numberentered = negativenumber;
}
numbersum = ( numberentered + numbersum ) - negativenumber;
}
while ( numberentered !=0 );
result = numbersum/count;
System.out.println ();
System.out.println ("*************************************");
System.out.println ();
System.out.println ("The sum of all of the numbers you entered is " +numbersum);
System.out.println ("You entered " + count + " numbers");
System.out.println ("The Average/mean of the numbers that you entered is " + result);
System.out.println ();
System.out.println ("*************************************");
}
}
any Ideas guys?
Thank you
The variable negativenumber always has the value zero. When you set numberentered to negativenumber the "while" condition is met, and the loop exits. A better strategy would be to us "continue" to skip the rest of the loop body when a negative number was entered.
If you want to ignore the negative number, then don't include it in your calculation. Instead do something like:
if (numberentered > 0)
{
numbersum += numberentered;
}
Examine the following block of code:
if (numberentered < 0)
{
numberentered = negativenumber;
}
What this is doing is setting numberentered to 0. Then, at the end of your do-while loop, you have this:
while(numberentered != 0);
So, whenever the user types in a negative number, you set numberentered to zero. When you reach the end of the loop, numberentered != 0 is false, so the loop exits.
The simpler solution, and something more akin to what you will learn to do on a regular basis in the future, is to simply check the value of the number in an if statement and then add it or not based on its value.
if(numberentered > 0)
numbersum += numberentered;
This is clean, concise, and removes the need for the negativenumber variable which is superfluous and could be confusing. If you were looking at this code a year from now, would you remember what negativenumber meant, or why it was set to zero? Write your code as if somebody else will have to read it and understand it. Your professors will, and, in the future, your colleagues will.
On another note, you are reading in integers (with inputLine.nextInt()) but storing them in a float. You've also declared count as a double. You most likely will want to declare count, numberentered, and numbersum as an int.
You never assign a value other than 0 (in initialization) to negativenumber, then you do
if (numberentered < 0)
{
numberentered = negativenumber;
}
and the do...while-loop terminates because numberentered is 0.

Categories

Resources