2015-11-05 113 views
-2

如果任何參數爲null,或者如果郵政編碼的字符不是數字,則構造函數將拋出IllegalArgumentException異常,並顯示消息「Invalid Address Argument」。郵編地址。 Java

Character.isDigit方法可以在執行此方法期間提供幫助。有關更多信息,請參閱Java API(字符類)。

我有非法參數異常關閉。但是,不是郵政編碼。幫幫我?

程序。

if(street==null||city==null||state==null){ 
     throw new IllegalArgumentException("Invalid Address Argument"); 
    } 

    if(zip == Character.isDigit(ch)){ 
    //To do??? 

    } 
+0

不是Java專家,但通過郵編作爲字符串和'int intZip = Integer.parseInt(zip)' – Frecklefoot

+0

哦,我不會拋出'null'參數的異常,我只是不會使用它們在我的地址計算if他們沒有提供。但我並不特別想要做什麼...... – Frecklefoot

+1

我假設'zip'是一個'String'。迭代通過'String'的'char's(通過調用'zip.toCharArray()')並檢查每個'char'是否是一個數字。如果沒有,請做你必須做的事情。 – Turing85

回答

0

嘗試阿帕奇StringUtils的

public static boolean isNumeric(CharSequence cs) 
Checks if the CharSequence contains only Unicode digits. A decimal point is not a Unicode digit and returns false. 

null will return false. An empty CharSequence (length()=0) will return false. 

StringUtils.isNumeric(null) = false 
StringUtils.isNumeric("")  = false 
StringUtils.isNumeric(" ") = false 
StringUtils.isNumeric("123") = true 
StringUtils.isNumeric("12 3") = false 
StringUtils.isNumeric("ab2c") = false 
StringUtils.isNumeric("12-3") = false 
StringUtils.isNumeric("12.3") = false 

Parameters: 
cs - the CharSequence to check, may be null 
Returns: 
true if only contains digits, and is non-null 
Since: 
3.0 Changed signature from isNumeric(String) to isNumeric(CharSequence), 3.0 Changed "" to return false and not true 
+0

我相當懷疑這個問題是一項家庭作業,並且學生被要求*實現一個方法來執行'StringUtils.isNumeric(...)'的作用* –

0
int zipcode = 0; 
try { 
    zipcode = Integer.parseInt(zipcode); 
}catch (Exception e){} 
if (zipcode <= 0) 
{ 
    throw new Exception(..); 
} 

如果你想成爲精確低於100萬。你使用的Char是沒有意義的,因爲你將會有一個字符串。

0

這聽起來像是對我的功課,所以我認爲你需要做的第一件事是學習如何閱讀文檔。讓我們把你的教練的提示,並查找的文檔Character.isDigit(char ch)

public static boolean isDigit(char ch) 

Handwaving遠一些條款存在的啓動,關鍵的事情是,該方法是static(這意味着我們這樣稱呼它Character.isDigit(myVariable),它返回boolean(true或false值),並且它接受char類型的參數。

所以,調用這個方法,我們需要一個char(單個字符)。我假設你zip變量是String。我們知道一個字符串是由多個字符組成的人物角色。所以我們需要的是從String一次一個地獲取這些字符的方法。您可以找到String類的文檔。here.

有幾種方法可以解決這個問題。我們可以使用toCharArray()得到一個數組中的字符,或者獲取特定的性格使用charAt(int index)

但是要解決它的字符串,你需要做到這一點(在僞代碼)

for each char ch in zip 
    if ch is not a digit 
     throw new IllegalArgumentException("Invalid Address Argument")