在这种情况下如何使用抛出异常?



对于这个赋值,它要求用户输入一个电话号码,然后将该号码分成每组整数的一个类别。我要做的是抛出一个简单的异常如果他们没有输入区号的括号它会抛出异常但不会使程序崩溃并要求他们使用正确的格式重新输入

public class App{
public static void main(String[] args) throws Exception {
Scanner input = new Scanner(System.in);

String inputNum;
String token1[];
String token2[];
String areaCode;
String preFix;
String lineNum;
String fullNum;

System.out.print("Enter a phone number in (123) 123-4567 format: ");

inputNum = input.nextLine();
System.out.println();

token1 = inputNum.split(" ");
areaCode = token1[0].substring(1, 4);
if (token1[0].substring(0, 3) != "()"){
throw new Exception("Enter a phone number in (123) 123-4567 format: ");
}

token2 = token1[1].split("-");

preFix = token2[0];

lineNum = token2[1];
fullNum = "(" + areaCode + ")" + " " + preFix + "-" + lineNum ;

System.out.print("Area code: " + areaCode + "n");
System.out.print("Prefix: " + preFix + "n");
System.out.print("Line number: " + lineNum + "n");
System.out.print("Full number: " + fullNum);
}
}

不用扔。不停地问就行了

String areaCode;
String preFix;
String lineNum;
while (true) {
System.out.print("Enter a phone number in (123) 123-4567 format: ");

String inputNum = input.nextLine();
System.out.println();

String [] token1 = inputNum.split(" ");
if (token1.length == 2 && token1[0].length() == 5
&& token1[0].charAt(0) == '(' && token1[0].charAt(4) == ')') {
areaCode = token1[0].substring(1, 4);
String [] token2 = token1[1].split("-");
if (token2.length == 2 && token2[0].length() == 3 && token2[1].length() == 4) {
preFix = token2[0];
lineNum = token2[1];
// If we reach this line all is ok. Exit the loop.
break;
}
}
}
String fullNum = "(" + areaCode + ")" + " " + preFix + "-" + lineNum ;
System.out.print("Area code: " + areaCode + "n");
System.out.print("Prefix: " + preFix + "n");
System.out.print("Line number: " + lineNum + "n");
System.out.print("Full number: " + fullNum);

最新更新