【问题标题】:If no value in textbox return String Java如果文本框中没有值返回 String Java
【发布时间】:2015-04-05 23:15:23
【问题描述】:

我必须比较一个字符串是否在插入的文本框中,如果不是,它应该返回一个字符串。它不适用于下面的这行代码,有人知道吗?

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();
          } 

【问题讨论】:

  • 请提供更多代码和您希望完成的任务的完整描述,以便充分评估和解决您的问题。

标签: java string return compare


【解决方案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 块之前。

【讨论】:

  • 这个答案检查了。作为旁注,inString.trim().length() == 0 会比inString.trim().isEmpty() 更好。
  • @dohaqatar7 我同意。已编辑。
  • 谢谢你,当我没有输入任何内容但它仍然没有保存数据时,我没有收到异常。我现在的问题是:它现在返回一个长度为 1 的字符串,对吗?我这样比较: if (msgYear.length() == 1 )
  • 我不确定您要将数据保存在哪里。我会把它作为一个单独的问题来问(当然是在接受我对这个问题的回答之后!)。
【解决方案2】:

假设inString 将保存在文本框中输入的字符串,我相信它应该是:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-21
    • 2013-04-19
    • 1970-01-01
    • 2018-06-28
    • 2018-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多