If else seems to be ignored in my java application - java

I just started programming in java and i am creating a simple waiting list.
it al seems to work well but i decided to include a if else construction to check the textfield not beeing empty. the problem is that it seems to be ignored because i don't get a error or something.. and i googled alot for the if else example and i can't solve the problem somehow.. what am i doing wrong? below you can find the relevant code. Thanks in advance.
public void actionPerformed(ActionEvent e) {
// check if veld1 is filled in.
if ( veld1 == null || veld1.equals( "" ) ) {
// give error
System.out.println("U heeft niets ingevuld in veld1");
}
else {
veld4.setText( veld3.getText() );
veld3.setText( veld2.getText() );
veld2.setText( veld1.getText() );
textveld1.append( veld4.getText() + "\n" );
veld1.setText("");
}
}

It seems veld1 is not a string, but some Swing control.
You probably want to do
if(veld1.getText() == null || veld1.getText().equals( "" )

It is difficult to grant without seeing the rest of it, but veld1.equals("") looks suspicious. You are comparing veld1 to the empty String, but veld1 looks like a component. Maybe you meant veld1.getText().equals("") (and, similarly, veld1.getText() == null)

If the veld1 holds a JTextField, you probably want to change the statement to veld1 == null || veld1.getText() == null || veld1.getText().equals( "" ), as in your current code you check if the field itself exists, not its content.

veld1.equals("") is not the same as veld1.getText().equals(""), the first one is comparing the veld1 object to an empty string, and will always be false.

Related

If condition statement erroring "There are coding standard violations (Java)

I am working on a customization where conditions are based on participant disability value "Y" and relation code child value "C".
Build Error points to: "There are coding standard violations" ;
Avoid using if statements without curly braces.
If client wants to display disability footnote on the page and dpnd is disable ; baseFtnt2 is the footnote that needs show.
I believe the error is in the syntax:
if (dpndEvntBean.getHasDpndDsbl()
&& item.getDsblCd().trim().equals("Y")
&& ddb.getRltnCd().trim().equals("C"));
{
ddb.addFtntIdListEntry("baseFtnt2");
}
Any help would be appreciated!
Thanks in advance
You should remove the ; at the end of the 3th line
if (dpndEvntBean.getHasDpndDsbl()
&& item.getDsblCd().trim().equals("Y")
&& ddb.getRltnCd().trim().equals("C")) // Removed ';'
{
ddb.addFtntIdListEntry("baseFtnt2");
}
otherwise it would mean
if (dpndEvntBean.getHasDpndDsbl()
&& item.getDsblCd().trim().equals("Y")
&& ddb.getRltnCd().trim().equals("C"))
{
}
{
ddb.addFtntIdListEntry("baseFtnt2");
}
So an empty block for the if and the ddb call called always.

Whats wrong with my syntax on if statement using LineReader?

Can anyone see why I'm getting an error on this:
r = new LineNumberReader(new FileReader(txtFile));
for (int i = 1; i < txtFile.length(); i++){
if (r.getLineNumber() = (6*i)+1 || r.equals(1)) {
//code here
}
}
Error is:
Multiple markers at this line
- The left-hand side of an assignment must be a
variable
- The left-hand side of an assignment must be a
variable
- Syntax error on token ")", delete this token
But i can't see whats the issue is. Error is on the 3rd line
EDIT: I love you all, you've saved me once again! Guess I've spent to long with VB.net....
if (r.getLineNumber() = (6*i)+1 || r.equals(1))
should be
if (r.getLineNumber() == (6*i)+1 || r.equals(1))
Not sure what do you want to check with this r.equals(1) but you will most probably get false all the time, since you are compartir equallity between a LineNumberReader and an Integer.
In JAVA you compare two objects with two equals == , but in the if statement you put only one =.
So replace the = in the second line with the ==.
And please, write down this error somwhere you can remember it. Becouse every time you'll see it, then you'll know that it is caused by this same problem (mostly).
My wild guess would be:
if (r.getLineNumber() == (6*i)+1 || r.getLineNumber == 1)
should be == in stead of =
r.getLineNumber() == (6*i)

Do while loop comparing Strings

I'm trying to do a "do while" loop with a nested if statement. I'm trying to compare two possible values for a String variable "word". If !word.equals "deeppan or thin" do something, else do something. But its not liking me using the or || comparator .. Any suggestions would be welcome.
do {
word = scan.next();
if ( !word.equalsIgnoreCase( "Deeppan" || "thin" ) ) {
System.out.print("Sorry you must specify a Deeppan or thin base, try again: ");
} else {
break;
}
} while ( true );
equalsIgnoreCase takes a single string argument, not a logical expression. You can combine them with || or && though:
if (!word.equalsIgnoreCase( "Deeppan") && !word.equalsIgnoreCase("thin" ))
You have to do it like this:
if (!word.equalsIgnoreCase("Deeppan") && !word.equalsIgnoreCase("thin")) {
Think about the || which i switched to &&, because the if should only be true, if the value is not the first AND not the second one!
This part is wrong, that's not how you use the boolean || operator, and anyway the logic is incorrect:
if (!word.equalsIgnoreCase("Deeppan" || "thin"))
It should be like this, comparison-operator-comparison, and notice the correct way to state the comparison for the effect you want to achieve:
if (!(word.equalsIgnoreCase("Deeppan") || word.equalsIgnoreCase("thin")))
Or equivalently, using De Morgan's laws (and easier to read and understand, IMHO):
if (!word.equalsIgnoreCase("Deeppan") && !word.equalsIgnoreCase("thin"))
You have a few issues going on. First:
"Deeppan" || "thin"
is attempting to use the boolean "OR" operator to compare two strings. The "OR" operator can only compare boolean results and returns a boolean that is the result of the comparison:
System.currentTimeMillis() == 123455667 || object.equals(this) // both sides are boolean results.
true || false // returns 'false'
But let's pretend for a second that "Deeppan" || "thin" is OK (remember, it isn't) and the compiler knows that you want to compare the two strings. It still leaves the issue that the OR operator returns a boolean result (true or false), which you are then attempting to pass into the method equalsIgnoreCase on the word variable. equalsIgnoreCase takes a String argument, not a boolean. This is the second compilation issue. As has been pointed out, what you need is to check for the conditions separately and OR the result to get the final boolean
if("Deeppan".equalsIgnoreCase(word) || "thin".equalsIgnoreCase(word)) {
// do something
}
("Deeppan" || "thin")
is a boolean expression. equalisIgnoreCase takes a string. Therefore you need to make two seperate calls and OR the (boolean) results

I don't understand why this simple statement isn't working

So I'm basically finished with a program, and at the end of it I'm printing Strings from an array to a file. The array may contain null values, so I'm checking for null before I print, but I keep ending up with 1 null at the very end of the file...
Here's the code I'm using to check for null
for(int i=0;i<array2.length;i++)
{
if(array2[i] != null)
out.println(array2[i]);
}
I know that the array contains multiple instances of null, but only 1 is being printed. I tried using the debugger and when array2[i] == null, it still entered the conditional statement...
So I added a println statement to help me see what's going on. It now looks like this:
for(int i=0;i<array2.length;i++)
{
if(array2[i] != null)
{
System.out.println("Adding " + array2[i]);
out.println(array2[i]);
}
Just after printing all the String values to the console, it prints "Adding null" so I know it's happening here in this if statement. Why is this happening???
The debugger is not always clear as to whether it has entered an if condition or not. I don't believe this code is entering the if condition which it might appear it is and your null is probably coming from another line of code.
You could write the code as
for(ElementType e: array2.length)
if(e != null)
out.println("[" + e+ ']'); // extra text for debugging.
// I suspect your `null` will still be on a line of its own
Arent you also missing a set of brakets for the if statement??
for(int i=0;i<array2.length;i++)
{
if(array2[i] != null)
{
out.println(array2[i]);
}
}

for each loop inside a if statement?

I've been getting an "illegal start of expression" error when trying to compile this for loop inside a if statement in java. Does anyone have any idea why?
if(letter.equals(" ") || letter == null ||for(String a: array){ letter.equals(a);})
Try
if( letter == null || letter.equals(" ") || checkArray(array, letter))
{
...
}
boolean checkArray(String[] arryay, String letter)
{
for(String a: array)
if(letter.equals(a))
return true;
return false;
}
Note: checking letter for null after you have already called equals() does not make too much sense; i've reordered those.
You cannot. Perhaps you should move the if statement into the for statement?
As rfausak said, a for statement does not return a boolean. You should have made that an answer by the way.
If you use a Set you could write:
if ( (letter.equals(" ")) || (letter == null) || (a.contains(letter)) ) {}
Well, that´s because you can not have a for loop within an if condition. It seems you want to see if the letter is within the array array; if so then you can do it with Apache commons-lang's ArrayUtils:
ArrayUtils.contains( array, letter );
This wont work because a for doesn't evaluate to a boolean. For readabilities sake you should extract that to a method anyway, good examples appear in other answers.
Other points, you should rejig your conditionals to not be susceptible to NullPointerExceptions
if (letter == null || " ".equals(letter) || arrayContains(array, letter)) {
//...
}
If you are able to add additional libraries, there are some nice apache commons libraries to make this work easier, namely StringUtils in commons-lang and CollectionUtils in commons-collections.
You also may like to harden that input checking if it's possible to get Strings larger than one character, by using String#trim() after checking for null. Again, this would be a good candidate for an extracted method isBlank(String str).

Categories