我会将字符导入到字符数组中,然后使用循环检查每个字符是否存在要为其抛出异常的字符类型。
下面的一些 sudo 代码:
private String getSSN(){
String tempSSN = scan.nextLine();
try {
char a[] = tempSSN.toCharArray();
for (int i = 0; i < a.length(); i++) {
if(a[i] != ^numbers 0 - 9^) { //sudo code here. I assume you want numbers only.
throw new exceptionHere("error message"); // use this to aviod using a catch. Rest of code in block will not run if exception is thrown.
}
catch (exceptionHere) { // runs if exception found in try block
System.out.print("enter a valid SSN without spaces or dashes.");
tempSSN= scan.nextLine();
}
return tempSSN;
}
我还会考虑在长度不是 9 个字符的数组上运行 if 。我假设您正在尝试捕获始终为 9 个字符的 ssn。
if (a.length != 9) {
throw ....
}
您可以在没有 try/catch 的情况下执行此操作。如果他们第二次输入无效的 ssn,上述内容将中断。
private String getSSN(){
String tempSSN = scan.nextLine();
char a[] = tempSSN.toCharArray();
boolean marker;
for (int i = 0; i < a.length(); i++) {
if(a[i] != ^numbers 0 - 9^) { //sudo code here. I assume you want numbers only.
boolean marker = false;
}
while (marker == false) {
System.out.print("enter a valid SSN without spaces or dashes.");
tempSSN = scan.nextLine();
for (int i = 0; i < a.length(); i++) {
if(a[i] != ^numbers 0 - 9^) { //sudo code here. I assume you want numbers only.
marker = false;
else
marker = true;
}
}
return tempSSN;
}
您可以选择以某种方式使用 contains 方法,我确信。
boolean marker = tempSSN.contains(i.toString()); // put this in the for loop and loop so long as i < 10; this will go 0 - 9 and check them all.