我會將字符導入到一個字符數組中,然後使用一個循環來檢查每個字符以查找您要拋出異常的字符類型。
一些須藤以下代碼:
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個字符陣列上。我假設你試圖捕獲總是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.