如果文本框中没有值,则返回字符串Java
我必须比较一个字符串是否在插入的文本框中,如果不是,它应该返回一个字符串。下面这行代码不起作用,有人有主意吗如果文本框中没有值,则返回字符串Java,java,string,return,compare,Java,String,Return,Compare,我必须比较一个字符串是否在插入的文本框中,如果不是,它应该返回一个字符串。下面这行代码不起作用,有人有主意吗 if (inString.trim().length() == 0) return "b"; 下面是整个代码块: public static String checkYear(String inYear) { // Gets the current date and time. // Returns the actual year as
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";
}
}
假设
inString
将保存在文本框中输入的字符串,我认为应该是:
if (inString ==null || (inString!=null && inString.trim().length() ==0))
return "b"
代码
if (inYear.trim().length() == 0)
return "b";`
if (inString == null || inString.trim().isEmpty())
return "b";
下线后就没有意义了
int year = Integer.parseInt(inYear);
如果inYear
只包含空格,则Integer.parseInt
将已抛出NumberFormatException
并捕获异常
代码
if (inYear.trim().length() == 0)
return "b";`
if (inString == null || inString.trim().isEmpty())
return "b";
应在
try
块之前进行操作。请提供更多代码和您希望完成的任务的完整描述,以便能够充分评估和解决您的问题。此答案已验证。作为旁注,inString.trim().length()==0
会更好,因为inString.trim().isEmpty()
@dohaqatar7我同意。编辑已完成。谢谢。现在,当我未输入任何内容但仍无法保存数据时,我不会收到异常。我现在的问题是:它现在返回一个长度为1的字符串,对吗?我这样比较:如果(msgYear.length()==1),我不确定要将数据保存到哪里。我会把它作为一个单独的问题来问(当然,在接受了我对这个问题的回答之后!)。