简体   繁体   中英

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. The do while loop in the main method is working properly but the do while loops in my get methods are not looping. 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.

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:

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:

 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:

 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. The getHours method is structured almost identical to the getHome method just with different variables and wording in the prompt. 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. 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. Thank you in advance for your help :)

Move the return statement to outside the loop:

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.

Also, be aware that this will allow 0 to be entered. Perhaps that's by design; perhaps an oversight. I can't tell.

Welcome to 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. You must move the return outside the loop for it to work correctly (or as intended):

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.
  • continue : when you continue , you'll go to next iteration; this only works in a loop.
  • break : when you break , you'll end the execution of a loop or a switch statement. For instance, if you had put break; instead of 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.

As an example of break , throw and continue :

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 .
  • The break could be replaced by a return homeRun;
  • The continue is useless in this case because there is nothing left after the try catch block.

Beside, if you are learning Java, you should perhaps read that because I think you are not doing think right. There exists GUI components that does the cumbersome work of handling input conversion for you.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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