Do-while loop problem

Please note that when I am comfortable with Java, I am not exceptionally gifted and do not know all the jargons, so please explain your answers with very little jargon coder and plain English or explain what jargon means after you use it ... Also, this is my first time with Stackoverflow, so let me know if this was a decent question and give me some pointers.

I am taking an AP Computer Science class at my high school. We are using Java. We were recently taught do-while loops and I just finished a "lab" that uses do-while loops, however there is a problem.

First, let me explain the lab. The program generates a random integer from 1 to 10 that the user has to guess (the guess is saved as an int using the scanner), there are several integer values ​​that keep track of the number of guesses, the number of guesses is greater than an integer number of computers, and how many were too few. When you look at my code, you will notice that I have System.out.println(compGen);//compGen is the computer generated int

. The goal was to test the code.

The problem is with the if statement which compares userGen (user guess) and compGen.

if(userGen==compGen)
{
//do a lot of stuff
}

      

In this if-statement, it doesn't print the correct SOPs I wrote if the user guesses multiple times. HOWEVER, I didn't write this into the program, it looks like it does it by itself. I used the SOP I mentioned earlier where compGen int is printed and I typed this as my first guess and it worked great. Everything in the if-statement block runs fine and prints correctly. However, when I did this as my second guess, third guess, or any guess that was not the first, NOTHING was printed. See the code below and run it. I don't think this should matter, but the IDE I am using is Eclipse, hence the package operator. Please, help.

    package Chapter_3.Lab03_Chapter3;
    import java.util.*;

public class Guess 
{
    public static void main(String[] args) 
    {   
    Scanner userInput = new Scanner(System.in);//Scanner
    int compGen = (int)(Math.random()* 10 + 1);//compGen is computer number
    System.out.println(compGen); //USED TO VERIFY FAILURE. VALUE WAS ENTERED TO TEST CODE
    int guessTrack = 0;//tracks number of guesses
    int tooHighTrack = 0;//CREATING INTS TO TRACK STUFF
    int tooLowTrack = 0;
    System.out.println("Welcome to the integer guessing game that everyoone loves!");//PROMPT 
    System.out.println("Please enter your guess for the integer. Remeber, it is between one and ten.");//GREETING
    int userGen = userInput.nextInt();//USER GUESS  

    do
    {
        guessTrack++;//Increase guess value
        if(userGen > compGen)//checks user value in relation to computer generated int
        {
            System.out.println("Try again! Your guess was too high!");//inform user of bad guess
            userGen = userInput.nextInt();//new guess
            tooHighTrack++;//if guess is too high, this int tracker increases
        }
        else if(userGen < compGen)//checks user value in relation to computer generated int
        {
            System.out.println("Try again! Your guess was too low!");//inform user of guess
            userGen = userInput.nextInt();//new guess
            tooLowTrack++;//increases if user guess is too low
        }
        else if(userGen==compGen)//if both values are equivalent, execute THIS IS THE PROBLEM STATEMENT!!
        {
            System.out.println("Great job! You guessed the right number!");//congratulate
            if(guessTrack>1)
            {
                System.out.println("It took you: "+guessTrack+" guess to get the right answer.");//print guess tracked int
            }
            else
            {
                System.out.println("It took you: "+guessTrack+" guesses to get the right answer.");//print guess tracked int
            }               
            System.out.println(tooHighTrack +" guesses were too high and "+ tooLowTrack+ " were too low.");//print how many guess were too big or too low
            System.out.println("HELLO"); //Used to verify failure of code
            userInput.close();//close scanner object
        }
    }
    while (userGen != compGen);//condition to be ultimately checked         
}
}

      

I couldn't figure out what was wrong. At some point, I removed the entire if statement and retyped it (I knew I wouldn't do anything, but I had to try). This question doesn't make any sense to me. There are no errors or anything that pops up, nothing appears on the console, which scares me a little. Thanks in advance.

+3
java loops do-while


source to share


5 answers


First, there is a lot of text that you put here. Maybe try to minimize the problem next time as a suggestion;) Otherwise everything will be fine

To your problem. Let me keep your code to a minimum and then explain to you what's going on.

1. Code

int val = scanner.nextInt();
do {
    if (val < 5) {
        // too low
        val = scanner.nextInt();
    } else if (val > 5) {
        // too high
        val = scanner.nextInt();
    } else {
        // correct
        // THIS CODE DOESN'T RUN?!
    }
} while (val != 5);

      

2. What does your code do?



You read your first number before your cycle. It's great. Then you enter the if-elseif-else statement. Note that once inside one of these blocks, the other blocks will not be executed. Now the problem is that you are reading your next custom inputs inside an if-elseif! The program reads the next value and leaves all if-elseif-else. Your code fails because the loop ends before the next iteration, so correct user input doesn't go through the if-elseif-else at all.

3. Solution

Remove all nextInt()

readings and just add them first inside the loop:

int val;
do {
    val = scanner.nextInt();
    if (val < 5) {
        // too low
    } else if (val > 5) {
        // too high
    } else {
        // correct
        // THIS CODE RUNS NOW!
    }
} while (val != 5);

      

Things like this, structures that need to execute something at least once before checking the condition of the loop, are usually done with loops do while

, not while

loops.

+5


source to share


You set user input during a loop and then validate it. Try to move the body of the block else if(userGen==compGen)

after the loop like this:



public static void main(String[] args) 
    {   
    Scanner userInput = new Scanner(System.in);//Scanner
    int compGen = (int)(Math.random()* 10 + 1);//compGen is computer number
    System.out.println(compGen); //USED TO VERIFY FAILURE. VALUE WAS ENTERED TO TEST CODE
    int guessTrack = 0;//tracks number of guesses
    int tooHighTrack = 0;//CREATING INTS TO TRACK STUFF
    int tooLowTrack = 0;
    System.out.println("Welcome to the integer guessing game that everyoone loves!");//PROMPT 
    System.out.println("Please enter your guess for the integer. Remeber, it is between one and ten.");//GREETING
    int userGen = userInput.nextInt();//USER GUESS  

    do
    {
        guessTrack++;//Increase guess value
        if(userGen > compGen)//checks user value in relation to computer generated int
        {
            System.out.println("Try again! Your guess was too high!");//inform user of bad guess
            userGen = userInput.nextInt();//new guess
            tooHighTrack++;//if guess is too high, this int tracker increases
        }
        else if(userGen < compGen)//checks user value in relation to computer generated int
        {
            System.out.println("Try again! Your guess was too low!");//inform user of guess
            userGen = userInput.nextInt();//new guess
            tooLowTrack++;//increases if user guess is too low
        }
    }
    while (userGen != compGen);//condition to be ultimately checked

    //The numbers have matched since it exited the loop.
    System.out.println("Great job! You guessed the right number!");//congratulate
    if(guessTrack>1)
    {
        System.out.println("It took you: "+guessTrack+" guess to get the right answer.");//print guess tracked int
    }
    else
    {
        System.out.println("It took you: "+guessTrack+" guesses to get the right answer.");//print guess tracked int
    }               
    System.out.println(tooHighTrack +" guesses were too high and "+ tooLowTrack+ " were too low.");//print how many guess were too big or too low
    System.out.println("HELLO"); //Used to verify failure of code
    userInput.close();//close scanner object
}

      

+3


source to share


The condition is while

checked as soon as the program reaches the end of the code inside the loop. Therefore, suppose they entered the wrong number; the program says it is too low or too high and then asks for another number:

userGen = userInput.nextInt();//new guess

      

Now, suppose this new number is correct. The program ends your statement if

and then gets to the end of the loop. Then at this point userGen

is compGen

. Thus, the condition while

fails and the program exits the loop immediately without receiving any code that prints the results.

One way to solve this problem is to move the logic for userGen == compGen

, which outputs the results outside the loop, that is, after the end of the loop. This way it will be executed whenever the loop is finished. Note that when you exit the loop, we know that userGen == compGen

, because if it weren't, the loop will return.

+1


source to share


Let's say the computer number was 3, and you guessed it 5.5> 3, so the if statement is executed (userGen> compGen):

        System.out.println("Try again! Your guess was too high!");//inform user of bad guess
        userGen = userInput.nextInt();//new guess
        tooHighTrack++;//if guess is too high, this int tracker increases

      

you print a message, get a new guess, and then increment your counter ... but when you get a new guess, let's say that the correct answer is 3, userGen is now CompGen (both are 3) and now and the condition is evaluated:

while (userGen! = compGen)

now it's false because userGen == compGen (both are 3). Your code never gets a chance to print the correct message because the loop exits before it can happen. hope it helps

+1


source to share


The userGen is not validated after each user input. The problem is that you have a check inside the else-if block that checks for the end of the while statement before it loops again.

If you change

else if(userGen==compGen)

      

to

if(userGen==compGen)

      

then, since it is not separated from the if-else block, it will be checked after every input (before the while condition is checked)

Alternatively, you can move your user input to the beginning of the do-while block like this:

package Chapter_3.Lab03_Chapter3;
import java.util.*;

public class Guess 
{
    public static void main(String[] args) 
    {   
    Scanner userInput = new Scanner(System.in);//Scanner
    int compGen = (int)(Math.random()* 10 + 1);//compGen is computer number
    System.out.println(compGen); //USED TO VERIFY FAILURE. VALUE WAS ENTERED TO TEST CODE
    int guessTrack = 0;//tracks number of guesses
    int tooHighTrack = 0;//CREATING INTS TO TRACK STUFF
    int tooLowTrack = 0;
    System.out.println("Welcome to the integer guessing game that everyoone loves!");//PROMPT 
    System.out.println("Please enter your guess for the integer. Remeber, it is between one and ten.");//GREETING
    int userGen = -1;//USER GUESS  

    do
    {
        userGen = userInput.nextInt();
        guessTrack++;//Increase guess value
        if(userGen > compGen)//checks user value in relation to computer generated int
        {
            System.out.println("Try again! Your guess was too high!");//inform user of bad guess
            userGen = userInput.nextInt();//new guess
            tooHighTrack++;//if guess is too high, this int tracker increases
        }
        else if(userGen < compGen)//checks user value in relation to computer generated int
        {
            System.out.println("Try again! Your guess was too low!");//inform user of guess
            userGen = userInput.nextInt();//new guess
            tooLowTrack++;//increases if user guess is too low
        }
        else if(userGen==compGen)//if both values are equivalent, execute THIS IS THE PROBLEM STATEMENT!!
        {
            System.out.println("Great job! You guessed the right number!");//congratulate
            if(guessTrack>1)
            {
                System.out.println("It took you: "+guessTrack+" guess to get the right answer.");//print guess tracked int
            }
            else
            {
                System.out.println("It took you: "+guessTrack+" guesses to get the right answer.");//print guess tracked int
            }               
            System.out.println(tooHighTrack +" guesses were too high and "+ tooLowTrack+ " were too low.");//print how many guess were too big or too low
            System.out.println("HELLO"); //Used to verify failure of code
            userInput.close();//close scanner object
        }
    }
    while (userGen != compGen);//condition to be ultimately checked         
}
}

      

This will cause your if-else block to be checked every time the user enters data before the do-while conditions are checked.

0


source to share







All Articles
Loading...
X
Show
Funny
Dev
Pics