2011-06-16 152 views
1

我想從一個函數中取多個參數,並檢查是否至少有一個參數不爲空或空。最好/最有效的方法來檢查是否至少有一個輸入是由用戶輸入

現在我正在做這樣的事情。

void foo(String a, String b, String c, String d, ... other strings){ 

//make sure at least one of the inputs are not null. 
if(a!=null || b!=null || c!=null || d!=null ... more strings){ 
    //do something with the string 
} 

} 

這樣的輸入可以是foo(null, null, null, "hey"); ,但它不能是foo(null, null, null, null);

什麼我的問題是有沒有更好的方式來做到這一點,而不是不斷增加的if語句。林消隱了現在....感謝

+0

多少個參數,你真的有這功能?這本身可能是一個問題。 – 2011-06-16 23:19:29

回答

3

使用varags

public static boolean atLeastOneEmpty(String firstString, String... strings){ 
     if(firstString == null || firstString.isEmpty()) 
     return true; 

     for(String str : strings){ 
     if(str == null || str.isEmpty()) 
      return true; 
     } 
     return false; 

    } 

返回true,如果至少一個字符串爲空

+0

+1你擊敗了我!我會修改它採取'公共靜態布爾atLeastOneEmpty(String str,字符串...字符串)'。使它更易讀易懂,至少需要一個參數。 – CoolBeans 2011-06-16 23:18:08

+0

好建議,編輯:) – 2011-06-16 23:21:31

+0

我認爲他需要相反的功能,atLeastOneNonEmpty,但你可以編輯這個答案。 – 2011-06-16 23:21:51

相關問題