do-while循环问题 [英] Issue with do-while loop

查看:100
本文介绍了do-while循环问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请注意,虽然我对Java感到满意,但我并不是特别有天赋,也不知道所有的术语,所以请用很少的编码器术语和尽可能多的普通英语来解释您的答案,或者在以后解释术语的含义你用吧.另外,这是我第一次使用Stackoverflow,所以请让我知道这是否是一个不错的问题,并给我一些指导.

Please note that I while I am comfortable with Java, I am not exceptionally gifted nor do I know all the jargon, so please explain your answers with very little coder jargon and as much normal English, or explain what the 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.

我正在读高中的AP计算机科学课.我们使用Java.我们最近被教过do-while循环,而我刚刚完成了使用do-while循环的实验",但是有一个问题.

I am taking an AP Computer Science class at my high school. We use Java. We were recently taught do-while loops and I just completed the "lab" that uses do-while loops, however, there is an issue.

首先,让我解释一下实验室.该程序会生成一个1-10之间的随机整数,用户必须猜测(使用扫描仪将猜测存储为int值),一些整数值来跟踪猜测的数量,多少个猜测大于计算机整数,以及有多少人太低了.当您查看我的代码时,您会注意到我有一个System.out.println(compGen);//compGen is the computer generated int.目的是测试代码.

Firstly, let me explain the lab. The program generates a random integer between 1-10 which the user must guess (guess is stored as an int using a scanner), there are a few integer values which track number of guesses, how many guesses were greater than the computer integer, and how many were too low. When you look at my code, you will notice that I have a System.out.println(compGen);//compGen is the computer generated int. The purpose was to test the code.

问题出在if语句中,该语句比较userGen(用户猜测)和compGen.

The issue is in the if-statement that compares userGen (user guess) and compGen.

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

在此if语句中,如果用户猜测不止一次,则它不会打印我编写的正确SOP.但是,我没有将其写到程序中,它似乎是自己完成的.我使用了我前面提到的SOP,在其中打印了compGen int,并且我第一次输入时就输入了它,并且效果很好. if语句块中的所有内容都可以完美执行并正确打印所有内容.但是,当我将其作为第二次猜测,第三次猜测或任何不是第一次的猜测时,便会打印出NOTHING.请参阅下面的代码并运行它.我不认为这会有所作为,但是我使用的IDE是Eclipse,因此是package语句.请帮忙.

In this if-statement, it is not printing the correct SOPs that I have written IF the user guesses more than once. HOWEVER, I did not write this into the program, it seems to do it on its own. I used the SOP I mentioned early where the compGen int is printed, and I typed that in as my first guess and it worked perfectly. Everything in the if-statement block executed perfectly and printed everything correctly. However, when I did it as my second guess, third guess, or any guess that was not the first one, NOTHING was printed. See code below and run it. I don't believe this should make a difference, but the IDE that I use is Eclipse, hence the package statement. 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         
}
}

我无法弄清楚出什么问题了.有一次我删除了整个if语句,然后重新键入(我知道它不会做任何事情,但是我必须尝试).这个问题对我来说毫无意义.没有错误或弹出的任何内容,控制台上没有弹出任何内容,这让我有些害怕.预先感谢.

I haven't been able to figure out what is wrong. At one point I deleted the entire if-statement and re-typed it (I knew it wouldn't do anything, but I had to try). This issue makes no sense to me. There are no errors or anything that pop up, nothing pops up on the console which scares me a little. Thanks in advance.

推荐答案

首先,您在此处输入了很多文本.也许下次建议尽量减少问题;)否则一切都很好

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

解决您的问题.让我最小化您的代码,然后向您解释会发生什么情况.

To your problem. Let me minimize your code and then explain to you, what happens.

1.代码

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.您的代码做什么?

您在循环之前先阅读了第一个数字.没关系.然后,输入if-elseif-else语句.请注意,一旦进入这些块之一,其他块将不会执行. 现在的问题是,您在if-elseif内部读取了下一个用户输入!该程序读取了下一个值,并留下了整个if-elseif-else.您的代码不会执行,因为循环会在下一次迭代之前结束,因此正确的用户输入根本不会通过if-elseif-else.

You read your first number before your loop. That's fine. Then, you enter an if-elseif-else statement. Note, that once inside one of those blocks, the other blocks won't get executed. Now the problem is, that you read your next user inputs inside of the if-elseif! The program reads the next value and leaves the whole if-elseif-else. Your code does not execute, because the loop then ends before the next iteration, therefore the correct user input is not going through the if-elseif-else at all.

3.解决方案

删除所有nextInt()读物,并将其中的第一件事作为 循环中的:

Remove all nextInt() reads and just have one as the first thing 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);

这类事情,在检查循环条件之前需要至少执行一次操作的结构,通常是通过do while循环而不是while循环

Such things, structures that need to do something at least once before checking the loop condition, are usually done with do while loops rather than while loops

这篇关于do-while循环问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆