Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exit from a do while loop in Java?

simple program to output number into phone number format I cant seem to exit the loop I'm not sure what I'm doing wrong I thought !PhoneNumber.equals("999"); would exit the loop when the user inputs 999 but it isn't working. Can anyone help me here's my code

import javax.swing.*;

public class PhoneNumberFormat 
{

    public static void main(String[] args) 
    {
      String PhoneNumber;
      int numLength= 10;

      do
      {

          PhoneNumber = JOptionPane.showInputDialog(null, 
                 "Enter your 10 digit phone number or enter 999 to quit");
          while(PhoneNumber.length() != numLength)
          {
              PhoneNumber = JOptionPane.showInputDialog(null,
                  "Error: You Entered " + PhoneNumber.length() + " digits\nPlease"
                      + " Enter a 10 digit Phone number");    
          }

            StringBuilder str = new StringBuilder (PhoneNumber);
            str.insert(0, '(');
            str.insert(4, ')');
            str.insert(5,' ');
            str.insert(9, '-');

        JOptionPane.showMessageDialog(null, "Your telephone number is " +str.toString());

      }while(!PhoneNumber.equals("999"));

    }
}
like image 363
BDoe Avatar asked Jan 17 '26 22:01

BDoe


1 Answers

If you wish to exist when the 999 you need to add an if condition to watch for it.

public static void main(String[] args) {
    String PhoneNumber;
    int numLength = 10;

    do {
        PhoneNumber = JOptionPane.showInputDialog(null,
                "Enter your 10 digit phone number or enter 999 to quit");

        // add this condition to exit the loop, as well protect against NPE
        if (PhoneNumber == null || PhoneNumber.equals("999")) {
            break;
        }

        while (PhoneNumber.length() != numLength) {
            PhoneNumber = JOptionPane.showInputDialog(null,
                    "Error: You Entered " + PhoneNumber.length()
                            + " digits\nPlease"
                            + " Enter a 10 digit Phone number");

            //protect against NPE
            if(PhoneNumber == null) 
               PhoneNumber = "";
        }

        StringBuilder str = new StringBuilder(PhoneNumber);
        str.insert(0, '(');
        str.insert(4, ')');
        str.insert(5, ' ');
        str.insert(9, '-');

        JOptionPane.showMessageDialog(null, "Your telephone number is "
                + str.toString());

    } while (!PhoneNumber.equals("999"));

}
like image 195
Raf Avatar answered Jan 20 '26 12:01

Raf