Infinite printing when trying to use a loop - java

new to programming.
I have a class in java and i'm trying to write this program but it's printing none-stop and it's even bugging my browser! (Im using an online ide)
my instructions:
Q: how much do you love me?
Below 10 : wrong answer
equal to 10 and more = good answer
I know how to do it but I dont want the program to stop every time i write an answer. I want the program to keep running until i have a 10 +. So i can always input until it's 10+ out of 10.
this is my lines :
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.println ("how much do you love me out of 10");
int num1 = input.nextInt();
while (true)
if (num1 <= 9) {
System.out.println("Wrong answer");
}
else {
System.out.println ("Good answer");
}
}
}

This should work:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner (System.in);
System.out.println ("Out of 10, how much do you love me?");
int input = 0
while (input <= 9) {
input = scanner.nextInt();
if (input <= 9) {
System.out.println("Wrong answer");
} else {
System.out.println("Good answer");
}
}
}
}
Explanation: It loops until input is less not less than or equal to 9 (while (input <= 9)). Each time through the loop, it gets input and acts on it.
Hope this helps!

First off, you need to move the int num1 = input.nextInt(); statement inside your while loop, this will allow for a new input every time the while loop loops (iterates).
Second, if you are looking to run the program until num1 >= 10, then you could implement it in two ways.
while(num1 < 10) {
num1 = input.nextInt();
if(num1 >= 10) {
System.out.println("Good answer");
} else {
System.out.println("Wrong answer");
}
}
or using the keyword break,
while(true) {
num1 = input.nextInt();
if(num1 >= 10) {
System.out.println("Good answer");
break;
} else {
System.out.println("Wrong answer");
}
}
break simply escapes the loop it resides in when called
Hoped this helped

Related

Using Random package

Okay, I want to create a simple game. I input a number, which was generated by PC using Random package and if I guess it, game over. But! I've no idea what is wrong with it.
import java.util.Scanner;
import java.util.Random;
public class Main {
static Scanner read = new Scanner(System.in);
public static void main(String[] args) {
int randomInt = new Random().nextInt(1000);
int userInput = -1;
System.out.println("I guessed a number\nYour turn: ");
while (randomInt != userInput) {
userInput = read.nextInt();
if (randomInt > userInput) {
System.out.println("Less than it");
} else if (randomInt < userInput){
System.out.println("More than that");
}
}
System.out.println("That's right!");
}
}
I used Debug and program worked. I mean, Random did his job, generated a number, but then it didn't show me "That's right!" output when I guessed a number. It just goes like "More that that" and "More that that"...
I ran it myself and it runs as expected. Maybe the confusion comes from the fact that you've switched up the places where you print "Less than it" and "More than that".
It should be like
while (randomInt != userInput) {
userInput = read.nextInt();
if (randomInt > userInput) {
System.out.println("More than that");
} else if (randomInt < userInput){
System.out.println("Less than it");
}
}
You got something wrong with the if statements. Also the scanner should be closed with read.close() to prevent memory leaks. Since there is no reason to put the scanner in the main class I also moved that to the main function. This should work for you know.
import java.util.Scanner;
import java.util.Random;
public class Main {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
int randomInt = new Random().nextInt(1000);
int userInput = -1;
System.out.println("I guessed a number\nYour turn: ");
while (randomInt != userInput) {
System.out.println(randomInt);
userInput = read.nextInt();
if (randomInt > userInput) {
System.out.println("More than it");
}
if (randomInt < userInput){
System.out.println("Less than that");
}
}
System.out.println("That's right!");
read.close();
}
}
The console message "More than that" prints if randomInt is less than user input (randomInt < userInput). Wouldn't you want it to print that if it is more than user input? The inverse condition applies to the other message. Could this be the issue? Otherwise, as already suggested, use a print statement to print the number out so you can test the correct guess.
I tried your code, and basically it works. The only problem I see is that you print the wrong string.
import java.util.Scanner;
import java.util.Random;
public class Test {
static Scanner read = new Scanner(System.in);
public static void main(String[] args) {
int randomInt = new Random().nextInt(10);
int userInput = -1;
System.out.println("I guessed a number\nYour turn: ");
while (randomInt != userInput) {
userInput = read.nextInt();
if (randomInt > userInput) {
System.out.println("More than it");
} else if (randomInt < userInput) {
System.out.println("Less than that");
}
}
System.out.println("That's right!");
}
}
Some tips:
Do not use such big numbers for tests
Instead of using a while loop use a do while loop

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 in a number guessing game

I need to write code that asks you to guess a number between 1 and 10 and uses a loop. It has to use the System.in.read() method to take user input. The correct number is 7, and when you guess that it ends. If you guess wrong it tells you to try again. I don't know why my code isn't working right, so I could use some help. The output I get is weird, no matter what number I enter it just says:
Hello! Enter a number between 1 and 10:
(entered number ex. 4)
Your guess is too high
Hello! Enter a number between 1 and 10:
Your guess is too high
Hello! Enter a number between 1 and 10:
I am new to programming so sorry if it isn't indented right or the solution is obvious.
public static void main(String[] args) throws java.io.IOException {
int input;
boolean play = true;
while (play == true) {
System.out.println("Hello! Enter a number between 1 and 10: ");
input = System.in.read();
if (input > 7) {
System.out.println("Your guess is too high");
} else if (input < 7) {
System.out.println("Your guess is too low");
} else if (input == 7) {
System.out.println("Correct! the correct number was: 7");
}
}
}
It should give you a specific result depending on the number, like if it is too high or low, then you can try again and enter a new number until you get the correct answer of 7. If the number isn't 1-10 you should get an error message. Thanks.
You're not changing the play variable, so there is no goin out of the while loop. You would have to change it like this:
else if (input == 7) {
System.out.println("Correct! the correct number was: 7");
play = false;
}
Also you might want to move this line: System.out.println("Hello! Enter a number between 1 and 10: "); before while loop.
This might solve your problem.
public static void main(String[] args) {
int input;
boolean play = true;
Scanner inputNumber = new Scanner(System.in);
while (play) {
System.out.println("Hello! Enter a number between 1 and 10: ");
input = inputNumber.nextInt();
if (input > 7) {
System.out.println("Your guess is too high");
} else if (input < 7) {
System.out.println("Your guess is too low");
} else if (input == 7) {
System.out.println("Correct! the correct number was: 7");
play = false;
}
}
}

Why is my do-while loop not working?

When I compile, that try to enter (y) to play again my do - while is not working, it takes me out of the loop.
import java.util.Scanner;
public class HiLo {
public static void main(String[] args) {
// Creating a play again variable
String playAgain = "";
// Create Scanner object
Scanner scan = new Scanner(System.in);
// Create a random number for the user to guess
int theNumber = (int)(Math.random() * 100 + 1);
int guessNumber = 0;
do
{
System.out.println("Guess a number between 1 - 100: ");
while (guessNumber != theNumber)
{
guessNumber = scan.nextInt();
if (guessNumber > theNumber)
{
System.out.println("Sorry, try again too high!");
}
else if (guessNumber < theNumber)
{
System.out.println("Sorry, try again too low!");
}
else
{
System.out.println("Congrats, you got it!");
}
}
System.out.println("Would you like to play again (y/n)?");
playAgain = scan.next();
} while (playAgain.equalsIgnoreCase("y"));
System.out.println("Thank you for playing! Goodbye.");
scan.close();
}
}
Change the code as below: (You just need to update the variables inside the loop)
public static void main(String[] args) {
// Creating a play again variable
String playAgain = "";
// Create Scanner object
Scanner scan = new Scanner(System.in);
// Create a random number for the user to guess
int theNumber = 0;
int guessNumber = 0;
do
{
// new lines to be added
theNumber = (int)(Math.random() * 100 + 1);
guessNumber = 0;
System.out.println("Guess a number between 1 - 100: ");
while (guessNumber != theNumber)
{
guessNumber = scan.nextInt();
if (guessNumber > theNumber)
{
System.out.println("Sorry, try again too high!");
}
else if (guessNumber < theNumber)
{
System.out.println("Sorry, try again too low!");
}
else
{
System.out.println("Congrats, you got it!");
}
}
System.out.println("Would you like to play again (y/n)?");
playAgain = scan.next();
} while (playAgain.equalsIgnoreCase("y"));
System.out.println("Thank you for playing! Goodbye.");
scan.close();
}
Here is the execution of code on Jshell:
The reason the program is not working is because the do-while loop does one iteration before it gets to the "while" part. In your case, the program successfully finishes the loop after a user correctly guesses the number. Your program breaks because after that you are requiring the user to enter 'y' to continue endlessly without letting them guess a number. If they guess a number, the program terminates.

Play Again feature not working

I can't seem to be able have my program ask the user if they would like to play again. The program ends when asking if they would like to continue. I added a break because before the program was continuously looping the correct answer and number of tries.
import java.util.Random;
import java.util.Scanner;
public class GuessTheNumber {
public static void main(String[] args) {
boolean play = true;
Scanner input = new Scanner(System.in);
Random Number = new Random();
int GuessNumber = 1+ Number.nextInt(1000);
int guess = 0;
int Tries = 0;
while(play) {
while(guess != GuessNumber) {
System.out.println("Please Enter a number between 1 and 1000:");
guess = input.nextInt();
Tries++;
if(guess == GuessNumber) {
System.out.println("You Win!");
break;
}
else if(guess < GuessNumber) {
System.out.println("Guess is too low");
}
else if(guess > GuessNumber) {
System.out.println("Guess is too high");
}
}
System.out.printf("Number was: %d",GuessNumber);
System.out.println("");
System.out.printf("Number of tries was: %d ",Tries);
System.out.println("");
System.out.println("Would you like to play again?(Yes/No)");
String playagain = input.nextLine();
if("Yes".equals(playagain))
play = true;
else
play = false;
}
}
}
A few things with your program.
As the comments have noted, you do need to flush your new-line character after using nextInt().
But, you must also set the guess value and try-count back to 0 after the user states that they would like to play again -- otherwise the program will just continue in a "You win!" loop.
I would recommend moving your variable declarations to the outer loop:
while(play) {
int guess = 0;
int guessNumber = 1 + Number.nextInt(1000);
int tries = 0;
...
}

Categories

Resources