用户输入验证java类

时间:2016-04-22 14:20:13

标签: java validation class

这是我对用户ID号的验证,在测试时,我输入了一个长度小于10的无效字符串,它设置输入并且不执行else语句。

源代码:

private String phoneNum;

public personalInfo(String phNum) {
    setPhoneNum(phNum);
}

public String getPhoneNum() {
    return phoneNum;
}

public void setPhoneNum(String phNum) {
    if (phoneNum.startsWith("05")&&(phoneNum.length()==10)){
        phoneNum = phNum;
    }
    else throw new IllegalArgumentException ("Invalid Phone Number!");
}

2 个答案:

答案 0 :(得分:1)

你的方法看起来像这样......

Exception in thread "SimpleAsyncTaskExecutor-1" 2016-04-22T16:20:53.646  WARN 15336 --- [cTaskExecutor-1] o.s.a.r.l.SimpleMessageListenerContainer : Consumer raised exception, processing can restart if the connection factory supports it
java.lang.NullPointerException: null
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.isActive(SimpleMessageListenerContainer.java:756) ~[spring-rabbit-1.4.3.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.access$600(SimpleMessageListenerContainer.java:82) ~[spring-rabbit-1.4.3.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer$AsyncMessageProcessingConsumer.run(SimpleMessageListenerContainer.java:1100) ~[spring-rabbit-1.4.3.RELEASE.jar:na]
    at java.lang.Thread.run(Thread.java:745) [na:1.8.0_77]

并且您没有验证参数,而是验证变量public void setPhoneNum(String phNum) { if (phoneNum.startsWith("05")&&(phoneNum.length()==10)){ phoneNum = phNum; } ...

改为:

phoneNum

答案 1 :(得分:0)

您应该验证您获得的值(phNum)并将其设置为成员变量phoneNum

if (phNum.startsWith("05")&&(phNum.length()==10)){
    phoneNum = phNum;
}