简体   繁体   English

Java做while循环不循环

[英]Java do while loops not looping

As far as I have read so far in my textbook for the class, in the modules for my class and in 2+ hours of searching, I cannot figure out why my code is not working. 据我到目前为止在班级教科书,班级模块中以及在2个小时以上的搜索中所读的内容,我无法弄清楚为什么我的代码无法正常工作。 The do while loop in the main method is working properly but the do while loops in my get methods are not looping. main方法中的do while循环正常工作,但我的get方法中的do while循环未循环。 I put in the wrong number, I get the error message and then instead of asking for the number again, it moves on to the next get method. 我输入了错误的数字,我得到了错误消息,然后继续输入下一个get方法,而不是再次请求该数字。

I hope it is something simple that I have overlooked but I would appreciate any help I could get on this. 我希望这是我忽略的简单事情,但是我会为此提供任何帮助,我将不胜感激。

Here is the code for my getHome method: 这是我的getHome方法的代码:

public static int getHome()
{

    int homeNum;
    String home;
     do
    {
        home = JOptionPane.showInputDialog(null,"Enter 1(apartment), 2(house),"
            + " or 3(dorm).","Dwelling Type", JOptionPane.QUESTION_MESSAGE);
        homeNum = Integer.parseInt(home);

        if(!(homeNum == 1) && !(homeNum == 2) && !(homeNum == 3))
        {    
            JOptionPane.showMessageDialog(null, "The value for dwelling type "
                + "must be 1(apartment), 2(house), or 3(dorm)", "Dwelling"
                        + "Type Error", JOptionPane.ERROR_MESSAGE);

        }              
        return homeNum;        
    }
    while(homeNum < 0 || homeNum > 3);

And the code in the main method that calls this method: 以及调用该方法的main方法中的代码:

 public static void main(String[] args)
{
    String response;

    do
    {
    petRec(getHome(), getHours());
    response = JOptionPane.showInputDialog(null, "Do you want to continue?" +
            "\nEnter Y for yes and anything else for no.", "Continue?", +
                    JOptionPane.QUESTION_MESSAGE);
    }
    while(response.equalsIgnoreCase("y"));


}

Just for clarification here is the petRec method: 为了澄清,这里是petRec方法:

 public static void petRec(int homeType, double hoursAtHome)
{


    String pet;

        if(homeType == 1 && hoursAtHome >= 10)
            pet = "Cat";
        else
        if(homeType == 1 && hoursAtHome < 10)
        pet = "Hamster";
        else
        if(homeType == 2 && hoursAtHome >= 18)
        pet = "Pot-Bellied Pig";
        else
        if(homeType == 2 && hoursAtHome >= 10 && hoursAtHome <= 17)
        pet = "Dog";
        else
        if(homeType == 2 && hoursAtHome < 10)
        pet = "Snake";
        else
        if(homeType == 3 && hoursAtHome > 6)
        pet = "Fish";
        else
        if(homeType == 3 && hoursAtHome < 6)
        pet = "Ant Farm";
        else
        pet = "Nothing";

    JOptionPane.showMessageDialog(null, "You should get a " + pet + "!",
            "Recommended Pet", JOptionPane.INFORMATION_MESSAGE);



}

Last year I took intro to Visual Basic and had infinite loops, this year I'm taking Java and can't get the loop to repeat. 去年,我参加了Visual Basic的介绍,并遇到了无限循环;今年,我使用了Java,无法重复循环。 The getHours method is structured almost identical to the getHome method just with different variables and wording in the prompt. getHours方法的结构几乎与getHome方法相同,只是提示中的变量和措词不同。 The program is supposed to display the error message when a number that is not 1, 2 or 3 is entered and then loop to ask you for the number again. 当输入的数字不是1、2或3时,该程序应该显示错误消息,然后循环以再次要求您输入该数字。 It displays the error message but then goes on to ask for the hours. 它显示错误消息,然后继续询问时间。 Again I very much appreciate any help that can be offered. 再次,我非常感谢可以提供的任何帮助。 This assignment isn't due until Saturday but I only have 2 days off to work on this. 这项作业要到周六才能完成,但是我只有2天的时间来做这项工作。 Thank you in advance for your help :) 预先感谢您的帮助 :)

Move the return statement to outside the loop: return语句移到循环外:

public static int getHome()
{
    int homeNum;
    String home;
    do
    {
        home = JOptionPane.showInputDialog(null,"Enter 1(apartment), 2(house),"
            + " or 3(dorm).","Dwelling Type", JOptionPane.QUESTION_MESSAGE);
        homeNum = Integer.parseInt(home);

        if(!(homeNum == 1) && !(homeNum == 2) && !(homeNum == 3))
        {    
            JOptionPane.showMessageDialog(null, "The value for dwelling type "
                + "must be 1(apartment), 2(house), or 3(dorm)", "Dwelling"
                        + "Type Error", JOptionPane.ERROR_MESSAGE);

        }              
    }
    while(homeNum < 0 || homeNum > 3);
    return homeNum;    
}    

As it is, you are returning from the method at the end of the first loop iteration. 照原样,您将在第一次循环迭代结束时从方法中返回。 You might also want to catch the potential NumberFormatException that can be thrown by the parseInt call. 您可能还想捕获parseInt调用可能引发的潜在NumberFormatException

Also, be aware that this will allow 0 to be entered. 另外,请注意,这将允许输入0。 Perhaps that's by design; 也许那是设计使然; perhaps an oversight. 也许是疏忽。 I can't tell. 我不知道

Welcome to Java: 欢迎使用Java:

do
{
    ...      
    return homeNum;        
}
while(homeNum < 0 || homeNum > 3);

In Java, the following instruction all finish the current statement: the code after will never be executed or you'll get an error. 在Java中,以下指令全部完成当前语句:之后的代码将永远不会执行,否则您将得到错误。 You must move the return outside the loop for it to work correctly (or as intended): 您必须将return移到循环外才能使其正常运行(或按预期运行):

do
{
    ...      
}
while(homeNum < 0 || homeNum > 3);
return homeNum;        
  • return : when you return a value, like in return homeNum, you exit the method in which you are. return :当您返回一个值时,例如在return homeNum中,您将退出当前所在的方法。
  • continue : when you continue , you'll go to next iteration; continue :当您continue ,您将进入下一个迭代; this only works in a loop. 这只能循环使用。
  • break : when you break , you'll end the execution of a loop or a switch statement. breakbreak ,您将结束循环或switch语句的执行。 For instance, if you had put break; 例如,如果您break; instead of return h omeNum; 而不是return h omeNum; the loop would have ended here. 循环将在这里结束。
  • throw new Exception("Foobar") : when you throw an error, it will exit the current try .. catch block method up one matching the exception kind. throw new Exception("Foobar")throw错误时,它将退出当前的try .. catch块方法,该方法与异常类型匹配。

As an example of break , throw and continue : 作为break的示例, throwcontinue

public static int getHome()
{
   int n = -1;
   for (;;) { // infinite loop powered !
     try {
       String home = JOptionPane.showInputDialog(null,"Enter 1(apartment), 2(house),"
                    + " or 3(dorm).","Dwelling Type", JOptionPane.QUESTION_MESSAGE);
       int homeRun =  Integer.parseInt(home);
       if(homeNum != 1 && homeNum != 2) && homeNum != 3) {
         // note: this is an example. You should NEVER use exception in these case
         throw new IllegalArgumentException("Damn!");
       }
       n = homeRun;
       break;

     } catch (NumberFormatException|IllegalArgumentException e) {
       JOptionPane.showMessageDialog(null, "The value for dwelling type "
             + "must be 1(apartment), 2(house), or 3(dorm)", "Dwelling"
                     + "Type Error", JOptionPane.ERROR_MESSAGE);       
       continue;
     }
  }
  return n;
}

This is an ugly example showing you the four instructions. 这是一个丑陋的示例,向您显示了四个说明。

  • Throwing an exception in this case is bad practise. 在这种情况下抛出异常是不好的做法。 But it'll go to the catch block because it catches the NumberFormatException (from Integer.parseInt ) and the thrown IllegalArgumentException . 但是它将转到catch块,因为它捕获了NumberFormatException (来自Integer.parseInt )和引发的IllegalArgumentException
  • The break could be replaced by a return homeRun; 休息可以用return homeRun;
  • The continue is useless in this case because there is nothing left after the try catch block. 在这种情况下, continue是没有用的,因为在try catch块之后没有剩余任何内容。

Beside, if you are learning Java, you should perhaps read that because I think you are not doing think right. 另外,如果您正在学习Java,则应该读一下,因为我认为您做的不正确。 There exists GUI components that does the cumbersome work of handling input conversion for you. 存在一些GUI组件,这些组件为您处理繁琐的输入转换。

Or even, instead of JOptionPane , you should rely on System.in and Scanner : it is pretty strange to execute a code in a terminal/console, then being asked in a window on some input, to then come back in the terminal/console. 甚至,而不是JOptionPane ,您应该依赖System.inScanner :在终端/控制台中执行代码,然后在某个输入窗口中被询问,然后再回到终端/控制台中,这很奇怪。 。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM