将号码输出为电话号码格式的简单程序 我似乎无法退出循环我不确定我做错了什么我想 !PhoneNumber.equals("999");当用户输入 999 但它不起作用时会退出循环。谁能帮我这是我的代码
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"));
}
}
最佳答案
如果您希望在 999 时存在,您需要添加一个 if 条件来监视它。
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"));
}
关于java - 如何退出 Java 中的 do while 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33788739/