While loops having trouble - java

I have tried my code like below..
public class GuessNumber {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Random rand = new Random();
int number = rand.nextInt(100) + 1;
int guess;
System.out.println("Guess the number between 1 and 100");
System.out.println("");
guess = scan.nextInt();
while (guess < number) {
System.out.println("Higher!");
guess = scan.nextInt();
}
while (guess > number) {
System.out.println("Lower!");
guess = scan.nextInt();
}
while (guess == number) {
System.out.println("Correct!");
break;
}
}
}
and I'm having trouble making it ask until the user gets the right number. And at the end for the game to ask if the user wants to play the game again

Your use of loops here
while (guess < number) {
System.out.println("Higher!");
guess = scan.nextInt();
}
while (guess > number) {
System.out.println("Lower!");
guess = scan.nextInt();
}
while (guess == number) {
System.out.println("Correct!");
break;
}
is creative. It happens to be flawed, but it's very creative. You need something like
while (guess != number) {
System.out.println((guess < number) ? "Higher!" : "Lower!");
guess = scan.nextInt();
}
System.out.println("Correct!");

The logic is not quite right. You want one while loop to check each condition and continue asking for a new number while the guess does not equal the number.
while (guess != number) {
if (guess < number)
System.out.println("Higher!");
else
System.out.println("Lower!");
guess = scan.nextInt();
}
System.out.println("Correct!");

while (true) {
if(guess < number)
System.out.println("Higher!");
else if(guess > number)
System.out.println("Lower!");
else if (guess == number){
System.out.println("Correct!");
}
guess = scan.nextInt();
}

you need only a single while loop. rearrange your logic in your loop.
boolean isRunning = true;
while(isRunning){
guess = scan.nextInt();
if(guess < number){
System.out.println("Higher!");
}else if(guess > number){
System.out.println("Lower!");
}else if(guess == number){
System.out.println("Correct!");
//ask if need another input. (want to continue or not)
if(not continue){
break; or isRunning = false;
}
}
}

Related

Limited number of possible choices?

Java newbie here.
There is this code (from tutorial) and i was wondering, what loop or other method i should use to limit max guess choices for example to 3?
I mean that user can guess only limited number of times and after that program just stops.
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int secretNum;
int guess;
boolean correct = false;
Scanner keybord = new Scanner(System.in);
System.out.print("GIVE ME SECRET NUMBER");
secretNum = keybord.nextInt();
while (!correct){
System.out.println("GUESS: ");
guess = keybord.nextInt();
if (guess == secretNum){
correct = true;
System.out.println("YOU ARE RIGHT");
}
else if (guess < secretNum){
System.out.println("HIGHER");
}
else if (guess > secretNum) System.out.println("LOWER");
}
}
}
You can keep track of the number of attempts with a counter like:
public static void main(String[] args) {
int attempts = 0;
Scanner keybord = new Scanner(System.in);
System.out.print("GIVE ME SECRET NUMBER");
int secretNum = keybord.nextInt();
while (true){
System.out.println("GUESS: ");
int guess = keybord.nextInt();
attempts++;
if (guess == secretNum){
System.out.println("YOU ARE RIGHT");
break;
}
if (attempts == 3) {
System.out.println("Max attempts!");
break;
}
else if (guess < secretNum){
System.out.println("HIGHER");
}
else if (guess > secretNum) System.out.println("LOWER");
}
}
It's very easy to do with your clean code structure. Declare a variable outside of your loop which will store the number of attempts. Then in your loop condition check amount of attempts and in the body increment this variable.
// Add
int attempts = 0;
// Update condition
while (!correct || attempts <= 3) {
// Update variable at the end of the loop
attempts++;
}
A do-while loop is best suited for this.
It is guaranteed to execute at least once, validate the loop condition at the end of the loop instead of the beginning, and it's easy to break out of any loop when you have breaking condition like this.
int guesses = 0;
final maxGuesses = 3;
final secretNum = ...
do {
System.out.println("GUESS: ");
guess = keybord.nextInt();
if (guess == secretNum){
System.out.println("YOU ARE RIGHT");
break; // no need for 'correct' value, just break out of the loop
}
else if (guess < secretNum){
System.out.println("HIGHER");
}
else if (guess > secretNum) System.out.println("LOWER");
}while (guesses++ < maxGuesses)
A for loop will also work. Here, guesses is checked before the loop starts, and increments at the end.
for(int guesses = 0; guesses < maxGuesses; guesses++){
System.out.println("GUESS: ");
guess = keybord.nextInt();
if (guess == secretNum){
System.out.println("YOU ARE RIGHT");
break;// no need for 'correct' value, just break out of the loop
}
else if (guess < secretNum){
System.out.println("HIGHER");
}
else if (guess > secretNum) System.out.println("LOWER");
}

Why this code prints an infinite amount of "What's your guess?"

I'm trying to make a number guessing game between the range from 1 to 100. The program will stop if the user guesses the correct number.
My current code:
import java.util.Scanner;
import java.util.Random;
public class GuessingGame {
public static void main(String[] args) {
Random randomNumber = new Random();
Scanner reader = new Scanner(System.in);
System.out.println("What's your guess? ");
int n = reader.nextInt();
reader.close();
int Number = randomNumber.nextInt(100 + 1);
int guess = n;
while (guess != Number) {
System.out.println("What's your guess? ");
new Scanner(System.in);
}
if (guess == Number) {
System.out.println("Your have guessed the correct number! ");
}
else if (guess < Number) {
System.out.println("Your number is too low! ");
}
else if (guess > Number) {
System.out.println("Your number is too high! ");
}
}
}
This is where using the formatter in your IDE is helpful. You would be able to see that the if conditions which are after the loop should be inside the loop and you should be reading the reading the guess from input.
BTW You should never close the input unless you explicitly don't want to read anything from it ever again.
try
Random randomNumber = new Random();
Scanner reader = new Scanner(System.in);
int number = randomNumber.nextInt(100 + 1);
while(true) {
System.out.println("What's your guess? ");
int guess = reader.nextInt();
if (guess == Number) {
System.out.println("You have guessed the correct number! ");
break; // no need to guess more
} else if (guess < Number) {
System.out.println("Your number is too low! ");
} else if (guess > Number) {
System.out.println("Your number is too high! ");
}
}
Change your while loop to
while (guess != Number) {
if (guess == Number) {
System.out.println("Your have guessed the correct number! ");
break;
}
else if (guess < Number) {
System.out.println("Your number is too low! ");
}
else if (guess > Number) {
System.out.println("Your number is too high! ");
}
System.out.println("Guess Again?");
guess = reader.nextInt();
}
The while loop is infinite loop. Also, you should avoid using 'Number' as variable name as there is a class in java with the same name java.lang.Number. You can also need any number of variables using single object of Scanner class. So, a cleaner code would look like this :
while (guess != number) {
System.out.println("What's your guess? ");
guess = reader.nextInt();
}
Now, if you solve above problems, your code will never go to the two else-if blocks, because by the time your while loop breaks you will have 'guess' always be equal to 'number'. I think what you are trying to achieve here is :
while (guess != number) {
System.out.println("What's your guess? ");
guess = reader.nextInt();
if (guess == number) {
System.out.println("Your have guessed the correct number! ");
}
else if (guess < number) {
System.out.println("Your number is too low! ");
}
else if (guess > number) {
System.out.println("Your number is too high! ");
}
}

How to use while loop

Ask the user to guess a number until the guess is equal random number. press 0 to quit and ask the user if they want to play again.
My problem, 0 for quit is, not working. How can I make it work with while loop?
thanks
import java.util.Random;
import java.util.Scanner;
public class Guessing
{
public static void main(String[]args){
String playAgain = "y";
final int MAX =100;
int randomNumber;
int numberofGuess = 0;
int guess ;
boolean flag=false;
Scanner input = new Scanner(System.in);
Random rand = new Random();
Scanner inputYes= new Scanner(System.in);
while(playAgain.equalsIgnoreCase("y"))//do
{
System.out.println("Guess a number between 1 and "+ MAX );
randomNumber = rand.nextInt(MAX) +1;
numberofGuess = 0;
System.out.println( "enter a guess(0 to quit):");
guess= input.nextInt();
numberofGuess++;
if(guess >0)
if (guess == randomNumber)
{
System.out.println("you guessed corect.");
System.out.println("you guessed " +numberofGuess+ " times");
}
else if(guess < randomNumber)
System.out.println("you guess is too low.");
else if(guess > randomNumber)
System.out.println("you guess is too high.");
System.out.println("Do you want to play again? (y/n)");
playAgain = inputYes.nextLine();
}//while(playAgain.equalsIgnoreCase("y"));
}
}
Your loop runs until the expression in parantheses is false:
while (true) {
// this will be executed forever
}
while (false) {
// this will never be executed
}
a = 0;
while (a == 0) {
a = 1;
// this will be executed exactly once, because a is not equal 0 on the second run
}
guess = 1
while (guess != 0) {
// this will executed until the user enters "0"
readln(guess);
}
Please keep in mind that this is pseudo code. It will not compile.

Java "Else without if" error. What did I do wrong?

public class GuessingGame {
public static void main(String[] args){
double randomNumber = Math.floor((Math.random()*100)+1);
Scanner userInputScanner = new Scanner(System.in);
do {
System.out.println("Enter your guess");
System.out.println("\n");
int Guess = userInputScanner.nextInt();
if(Guess == randomNumber)
System.out.print("Good");
System.out.print("\n");
else if(Guess < randomNumber)
System.out.print("Higher");
System.out.println("\n");
else if(Guess > randomNumber)
System.out.print("Lower");
System.out.println("\n");
}
while(Guess != randomNumber);
}
}
add brackets {} around if and if else body, Java doesn't work like python in if else and indentation
if(Guess == randomNumber) {
System.out.print("Good");
System.out.print("\n");
} else if(Guess < randomNumber) {
System.out.print("Higher");
System.out.println("\n");
} else if(Guess > randomNumber) {
System.out.print("Lower");
System.out.println("\n");
}
It should be like this:
if(Guess == randomNumber){
System.out.print("Good");
System.out.print("\n");
}else if(Guess < randomNumber){
System.out.print("Higher");
System.out.println("\n");
}else if(Guess > randomNumber){
System.out.print("Lower");
System.out.println("\n");}
With the braces around if-else.
The problem is you're trying to put multiple statements inside an if block without curly braces. In other languages, the indentation controls the structure, but Java is free-form, so without braces, only one statement is grouped to each if/else.
So the program groups the first statement to the if, then the next statement is alone, then you have an else without an immediately preceding if.
You need to add {} after every if condition and Guess variable need to declare before do while
here the complete code , already compile it and nothing wrong
import java.util.Scanner;
public class GuessingGame{
public static void main(String[] args){
double randomNumber = Math.floor((Math.random()*100)+1);
Scanner userInputScanner = new Scanner(System.in);
int Guess = 0;
do{
System.out.println("Enter your guess");
System.out.println("\n");
Guess = userInputScanner.nextInt();
if(Guess == randomNumber) {
System.out.print("Good");
System.out.print("\n");
}
else if(Guess < randomNumber) {
System.out.print("Higher");
System.out.println("\n");
}
else if(Guess > randomNumber) {
System.out.print("Lower");
System.out.println("\n");
}
}
while(Guess != randomNumber);
}
}

Turn while loop number game into a do while loop number game [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I made a number game using while loops but I am told I am supposed to do with with do while instead. I was wondering how I could transfer it from this format to do while.
import java.util.Scanner;
public class SS_Un6As2 {
public static void main(String[] args) {
int guess = 0;
int randomNumber = (int) (Math.random() *100) +1;
Scanner scan = new Scanner(System.in);
boolean running = true;
while(running){
System.out.println("Guess your number");
guess = scan.nextInt();
if(guess == randomNumber) {
System.out.println("You are correct");
break;
}
else if (guess > randomNumber){
System.out.println("Too high.");
}
else if (guess < randomNumber){
System.out.println("Too low");
}
else {
System.out.println("Try again");
}
}
System.out.println("Thanks for playing");
}
}
Solution to your problem
while(running){
System.out.println("Guess your number");
guess = scan.nextInt();
if(guess == randomNumber) {
System.out.println("You are correct");
break;
}
else if (guess > randomNumber){
System.out.println("Too high.");
}
else if (guess < randomNumber){
System.out.println("Too low");
}
else {
System.out.println("Try again");
}
}
Becomes
do {
System.out.println("Guess your number");
guess = scan.nextInt();
if(guess == randomNumber) {
System.out.println("You are correct");
break;
}
else if (guess > randomNumber){
System.out.println("Too high.");
}
else if (guess < randomNumber){
System.out.println("Too low");
}
else {
System.out.println("Try again");
}
}
while(running);
The Difference
In a while loop, the code can run 0-* times. (0 to many). In a do-while loop, the code can run 1-* times.
Stack overflow ethos
Try to think of this place as more of a last resort. I googled do while loop java and the first link was this which explains your issue perfectly. In future, perhaps you should use your own methods of research before you rely on ours.
Edit for you
A for loop is different, in that it will run x times. Like so:
for(int x = 0; x < 5; x++)
{
System.out.println("Hello " + x);
}
/**
* OUTPUT:
* Hello 0
* Hello 1
* Hello 2
* Hello 3
* Hello 4
*/
Applying While loops to your problem
The do-while loop has a conditional statement in it, inside the while.
do {
}
while(something is true)
Think of that as your if statement. Now you want that to be true, until the person has guessed 12 times. It only logically follows that you want to keep count of the number of guesses, so we'll introduce an int called guesses. And you only want guesses to reach 12 and no more, so this is where we'll go from.
do {
// Some code goes here.
guesses ++;
// Increase the number of guesses if they got it wrong.
}
while(correct = false && guesses < 12)
What I've done is made up a variable called correct, that tells if the person got it right or not. And I increase the value in guesses each time they make a guess that's wrong. That means the loop will only stop if:
The person guesses correctly
The person had 12 attempts
do{
System.out.println("Guess your number");
guess = scan.nextInt();
if(guess == randomNumber)
{
System.out.println("You are correct");
break;
}
else if (guess > randomNumber)
{
System.out.println("Too high.");
}
else if (guess < randomNumber)
{
System.out.println("Too low");
}
else
{
System.out.println("Try again");
}
} while(running);
In you case it is pretty easy:
boolean running = true;
do {
System.out.println("Guess your number");
guess = scan.nextInt();
if(guess == randomNumber) {
System.out.println("You are correct");
break;
}
else if (guess > randomNumber){
System.out.println("Too high.");
}
else if (guess < randomNumber){
System.out.println("Too low");
}
else {
System.out.println("Try again");
}
} while (running)
In general you can transform an arbitrary while loop into do-while loop in following way:
while (condition) {
...
}
will become
if (condition) {
do {
...
} while (condition)
}
If you're using break when you guess the random number, then there's no point of using running as a control to break out of the loop. I would simply change running when that happens. Also, the line where you print out "Try again" will never be run, so you could remove that else block. It would look like this.
do{
System.out.println("Guess your number");
guess = scan.nextInt();
if(guess == randomNumber)
{
System.out.println("You are correct");
running = false;
}
else if (guess > randomNumber)
{
System.out.println("Too high.");
}
else if (guess < randomNumber)
{
System.out.println("Too low");
}
} while(running);

Categories