Tuesday, 15 May 2012

Java if statement always returns true -



Java if statement always returns true -

i trying validate input swing form checking null values. checkfirstname method returning true. illustration if leave firstname blank on form homecoming true though field null.

here 2 methods, first 1 fired when user clicks save button.

public void savenewcustomer() throws sqlexception, classnotfoundexception { boolean dbok = false;//boolean check if info input not null system.out.println(dbok); string firstname = txtncustomerfirstname.gettext(); string lastname = txtncustomerlastname.gettext(); if (checkfirstname(firstname)) { dbok = true; } else { lblncustfirstnameerror.settext("first name must entered"); dbok = false; } system.out.println(dbok); if (dbok) { dbconnector.insertsignup(firstname, lastname); system.out.println("success"); } else { system.out.println("error"); } } public boolean checkfirstname(string firstname) { boolean allok = false; system.out.println(allok); if (firstname != null) { allok = true; } else { allok = false; } homecoming allok; }

have done wrong cause me should homecoming false cause firstname field null.

so illustration if leave firstname blank on form

you checking null, need empty ("") string check also.

it should like:

if (firstname != null && !"".equals(firstname.trim()) {

java if-statement null

No comments:

Post a Comment