如果 string.contains() 正确,如何中断嵌套循环

how to make a nested loop break if string.contains() is correct

我在理解嵌套循环及其行为时遇到问题。在第一个循环中,脚本要求输入 10 位数字,否则它将继续循环,这很好用。在第二个循环中,我试图让程序保持 运行 直到用户在 phone 数字的任何位置输入“999”。我有一些想法,但我无法将它们放在一起。因此,如果用户输入一个 10 位数字但不包含 999,那么它会不断要求重新输入 phone 号码。

    import javax.swing.JOptionPane;
    import java.lang.*;


      public class FormatPhoneNumber {


      public static void main(String[] args) {
      final int numLength=10;
      String phoneNum = null;
      String nineS="999";



        phoneNum=JOptionPane.showInputDialog(null, "Enter your telephone number");

            while (phoneNum.length()!=numLength)

        {phoneNum=JOptionPane.showInputDialog(null, "You must re-enter 10 digits as your telephone number.");
        }


        StringBuffer str1 = new StringBuffer (phoneNum);
        str1.insert(0, '(');
        str1.insert(4, ')');
        str1.insert(8, '-');

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

              while (phoneNum.contains(nineS))// THIS IS THE ISSUE
              {

        }
      }
 }

使用

if (phoneNum.contains(nineS))
 {}

不要使用

while (phoneNum.contains(nineS))  

或者你可以这样做

if (!(phoneNum.contains(nineS)))
          {
            JOptionPane.showMessageDialog(null,"Invalid Input");
          }    

嵌套是指一个循环在另一个循环内。您提供的代码没有。

嵌套的典型例子:

while( some_condition )
{ 
    do_something..
    while( more_condition )
    {
        do_something_more..
    }
}

如果我没理解错的话,你想继续输入数字并用它们做点什么。但是一旦用户输入其中包含“999”的数字,控件就必须跳出循环。

正如有人已经指出的那样,您根本不需要嵌套循环来实现这一点。

while( phoneNumber has 10 digits )
{
     do_something..
     if( phoneNumber has '999' anywhere )
     {
         break;
     }
}
while (phoneNum.length()!=numLength)
    {
        phoneNum=JOptionPane.showInputDialog(null, "You must re-enter 10 digits as your telephone number.");

        StringBuffer str1 = new StringBuffer (phoneNum);
        str1.insert(0, '(');
        str1.insert(4, ')');
        str1.insert(8, '-');

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

          if(phoneNum.contains(nineS))// THIS IS THE ISSUE
            break;
    }

希望对您有所帮助。