2013-01-18 69 views
1

java, 是否有可能檢查一個字符串上有特殊字符或字母,如果是的話拋出異常?是否一個字符串有數字或特殊字符並拋出異常

這樣的事情,但使用的try/catch

/** Get and Checks if the ssn is valid or not **/ 
    private String getSSN(){ 
     String tempSSN; 
     tempSSN = scan.nextLine(); 
     if(tempSSN.matches("^.*[^a-zA-Z ]{9}.*$") == false){ 
      System.out.print("enter a valid SSN without spaces or dashes."); 
      tempSSN= scan.nextLine(); 
     } 
     return tempSSN; 
    } 

回答

1

如果你能做到這一點沒有異常處理,對於爲什麼要使用一個try-catch塊沒有明顯的理由。但是如果你想拋出一個異常,使用try-catch塊不是必須的。您可以使用throw

if(something) { 
     throw new SomeAppropriateException("Something is wrong"); 
    } 

,如果你想捕捉異常並記錄任何錯誤或消息,並繼續執行,你可以使用catch塊。或者當你想拋出其他有意義的異常時,你發現異常。

0

我會將字符導入到一個字符數組中,然後使用一個循環來檢查每個字符以查找您要拋出異常的字符類型。

一些須藤以下代碼:

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. 
相關問題