2015-04-05 16 views
0

我必須比較一個字符串是否插入到文本框中,如果沒有,它應該返回一個字符串。它不適用於下面這行代碼,有一個想法?如果文本框中沒有值返回String Java

if (inString.trim().length() == 0) 
      return "b"; 

這裏是代碼的整個塊:

public static String checkYear(String inYear) { 


     // Gets the current date and time. 
    // Returns the actual year as an int. 
    Calendar now = Calendar.getInstance(); // Gets the current date and time. 
    int currYear = now.get(Calendar.YEAR); 
    try 
    { 
     int year = Integer.parseInt(inYear); 

     if (inYear.trim().length() == 0) 
       return "b"; 


      if ((year >= 1900) && (year <= currYear)) 
      return ""; //valid date 
      else 
      return "Year must be between 1900 and current year"; 

    } 
    catch (Exception ex) 
    { 
     return "Year must be a Number"; 
    } 

} 

我已經得到一個異常。

我測試,如果沒有什麼是這段代碼的文本塊中:

String year = txtYear.getText(); 
    String msgYear = DVD.checkYear(year); 
    int year2 = 0; 

if (msgYear.length() == 1) 
      { 
       year2 = 0; 

      DVD dvd2 = new DVD(txtTitle.getText(), 
          year2, 
         favouriteCheck); 
      dvdCollect.addDVD(dvd2);     
      parent.refreshDVDList(); 
      } 
+0

請提供更多的代碼和完整的描述,說明您希望完成什麼,以便您的問題得到充分評估和解決。 – 2015-04-05 23:19:29

回答

1

代碼

if (inYear.trim().length() == 0) 
      return "b";` 

行後沒有意義

int year = Integer.parseInt(inYear); 

如果inYear由無非是空白,Integer.parseInt將已經拋出NumberFormatException和捕捉到的異常。

代碼

if (inString == null || inString.trim().isEmpty()) 
    return "b"; 

try塊之前應該去。

+0

這個答案檢查出來。作爲一個方面說明,'inString.trim().length()== 0'會比'inString.trim()。isEmpty()'更好。 – 2015-04-05 23:36:43

+0

@ dohaqatar7我同意。編輯。 – 2015-04-05 23:38:31

+0

謝謝您現在,我沒有輸入任何內容,但仍未保存數據。我現在的問題是:它現在返回一個長度爲1的字符串對嗎?我比較像那樣:if(msgYear.length()== 1) – Taurus2000 2015-04-05 23:43:28

-1

假設inString將持有的字符串在文本框中輸入,我相信它應該是:

if (inString ==null || (inString!=null && inString.trim().length() ==0)) 
    return "b"