If statements not being detected - java

I am using Netbeans 7.1.2 IDE.
My code is here:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String search1;
search1 = jTextField1.getText();
search1.toLowerCase();
jTextField2.setText("tes1");
// stone
if (search1=="stone" || search1=="rock" || search1=="1")
{
jTextField2.setText("Stone: 1");
}
// grass
else if (search1=="Grass" || search1=="grass")
{
jTextField2.setText("Grass: 2");
}
// dirt
else if (search1=="Dirt" || search1=="dirt" || search1=="Soil" || search1=="soil")
{
jTextField2.setText("Dirt: 3");
}
// cobblestone
else if (search1=="cobblestone" || search1=="cobble")
{
jTextField2.setText("Cobblestone: 4");
}
else;
{
jTextField2.setText("Unknown Block");
}
}
When I run the build, and I input 'stone' into jTextField1, and hit jButton1, it just gives me "Unknown Block", when an If statement specifies that it should set jTextField to "Stone: 1". Am I doing something wrong? Sorry if this ends up being a completely obvious error.

Compare String using equals()
if (search1.equals("stone") || search1.equals("rock") || search1.equals("1"))
Read this for more information.
== compares references,not the values. In your case, you want to check for the value equality, not the reference equality.
EDIT:
Remember, you need to do all your String comparisons that way.
Besides,
you have an unwanted ; here:
else;
{
jTextField2.setText("Unknown Block");
}
remove that ; after else.

You need to use the .equals to check strings, like so:
if (search1.equals("stone") || search1.equals("rock") || search1.equals("1"))

So first don't compare String using == but use equals() instead then in the last else statement you have add a ; that means the end of the else (so jTextField2.setText("Unknown Block") is always executed). You should drop it.
else; //<==Remove the ;
{
jTextField2.setText("Unknown Block");
}

You should do what Kazekage Gaara is telling. But in this instance the problem is not that. in the following statement remove the ; after else.
else;
{
jTextField2.setText("Unknown Block");
}
What happens here is
{
jTextField2.setText("Unknown Block");
}
gets executed anyway because it's after the if else blocks. Semicolon effectively terminates the else statement.

Use .equals instead of == to comapre strings.
See: http://blog.enrii.com/2006/03/15/java-string-equality-common-mistake/

Related

If-then-else statement use

Method: “run”
Create endless loop
If MerkleManager.sMerkleRoot is not null then...
If the above merkle root equals the initial user-entered merkle root.Then print out “You win: “ followed by the merkle root and exit the app.
Else if they’re not equal, then tell the user he lost – and exit the app.
My code:
public void run() {
while (true) {
}
if MerkleManager.sMerkleRoot = null;
{
} else {
}
System.exit(0);
}
How do I set MerkleManager.sMerkleRoot not null and use if-then-else statement?
In your check you are assigning the value of MerkleManager.sMerkleRoot with "=" assignment operand.
Instead you should be checking "==" or "!=" operand to compare the object references.
public void run() {
while (true) {
}
if MerkleManager.sMerkleRoot != null
{
} else {
}
System.exit(0);
}
Your code will never leave the while loop the way it's written.
Change to this,
public void run() {
while (true) {
if MerkleManager.sMerkleRoot != null{
// do stuff
}else {
// do something else
}
System.exit(0); // if you leave this statement, your code will exit on the first exec
}
First off, you are saying that you want it to exit the JVM whether the condition is met or not which would render the while loop useless as the first iteration would guarantee a termination for either case (and the way you have it currently will get you stuck in the loop and never execute the following line anyways) so you can remove that completely.
Second, you need parentheses around the boolean statement in an if clause in java.
What you want to do for your method might look a little more like this
public void run() {
if (MerkleManager.sMerkleRoot != null && MerkleManager.sMerkleRoot == inputRoot) {
System.out.println("You won");
}
else {
System.out.println("You lose");
}
System.exit(0);
}

Return statement function in if conodition

In my code:
if (id.isEmpty() || name.isEmpty()) {
warlbl.setText("Warning, Empty ID or Name Fields");
return;
}
id and name are String that give from JTextFields ,
Is necessary use return; in here or Not?
Yes, it can be:
if (...) {
...
return;
}
// nothing at this point will be reached if the if-statement is entered
vs.
if (...) {
...
}
// code here will still be reached!
return exits the current method you are "in".
Of yource it is not necessary but maybe you want to exit the method if id.isEmpty() and name.isEmpty(). So no and yes. It is not neccassary but you may want to return
You can use return to break out of a method, continue to skip a loop or a break to break out of a block.
Often there are 2 ways:
public void test() {
if (!statement) {
// to something if statement is false
} else {
//we failed, maybe print error
}
}
or:
public void test() {
if (statement) {
//we failed, maybe print error
return;
}
//do something if statment is false
}
But this is more a kind of "style". Mostly I prefere the second way, just because it's less spagetti :P
Keep in mind. If your return statement would be the last statment executed it's redundant.
Java reference:
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html

How avoid multiple IF loops in Java [duplicate]

This question already has answers here:
Avoiding NullPointerException in Java
(66 answers)
Closed 9 years ago.
What is the best way to avoid multiple if blocks which is used for null checks in Java?
The following is my sample code. Which one is the most optimized way?
if (address!=null} {
if (firstName!=null) {
if (lastName!=null) {
}
}
}
Use &&. && is logical and. && combines two values and returns a boolean which is true if and only if both of its operands are true
if(address!=null && firstName!=null && lastName!=null)
{
}
For instance
boolean b;
b = 3 > 2 && 5 < 7; // b is true
b = 2 > 3 && 5 < 7; // b is now false
if loop is a wrong word. You should say if statements As in you case you can use OR (||) or AND (&&)statement like this
if(address!=null && firstName!=null && lastName!=null)
{
}
Try AND(&&) if you want to pass all checks or intead of nested if statements and try OR(||) for non nested like else if or simply say if you want to pass anyone of your condition But
if all of these are Strings then you should try like this
"yourValue".equals(stringValue)This will skip the null check.
Use and operator (&&)
if(address!=null && firstName!=null && lastName!=null)
{
//DoSomething here
}
And I suggest you to see Short circuit evaluation
there are no if LOOPS
boolean complete = address != null && firstName != null && lastName != null;
if (complete)
{
}
What about:
public boolean notNulls(Object ... args) {
for(Object arg : args)
if (arg == null) return false;
return true;
}
Use:
if (notNulls(address, firstName, lastName)) {
// do something
}
As others point out, a logical and (&&) is probably the best way to consolidate your logic. An && operation will only evaluate to true if both sides evaluate to true.
if (address != null && firstName != null && lastName != null) {
// Whatever you want to do with that...
} else {
// Whatever you want to do with bad input
}
For the sake of diversity, you could also use a try-catch approach. In Java, a NullPointerException will be thrown if you try to call a method on a null value, which you can catch and handle.
try {
// Whatever you want to do with that...
} catch (NullPointerException npe) {
// Whatever you want to do with bad input
}
This approach can be helpful if you've got a really big set of inputs that might be null, although in general I wouldn't advocate it. (The problem with the second approach is that if you call some other method from the try part that triggers a NullPointerException, it will end up in the catch block here, even though it may be totally unrelated to these inputs - i.e. you could make it hard for yourself to spot a bug in a different part of your program.)

How to write (if, if, if) else if none

I'm trying to make a group of if statements, in which each if will print given some argument is true, but an else that will only print if none of the ifs were returned. I don't think an else if would work in this case.
I have some code (the colors are just as examples):
boolean any=false;
if(redStage==2)
{ any=true; System.out.print(redComplete); }
if(blueStage==2)
{ any=true; System.out.print(blueComplete); }
if(greenStage==2)
{ any=true; System.out.print(greenComplete); }
if(any==false)
System.out.print(noneComplete);
Is there anything I can do to eliminate the need for a separate boolean to check whether any of the if's arguments were true?
Edit:
(I just noticed what may be confusing. The code im using isn't actually using return. Instead, it is printing out the results, which means more than one thing can be returned.)
Since you need to processes the stages independently from one another, and more than one can be complete at the same time, your code is as good as it can be.
What follows is my answer to your original question:
You don't need the boolean. Your code is equivalent to:
if (redStage == 2) { return redComplete; }
if (blueStage == 2) { return blueComplete; }
if (greenStage == 2) { return greenComplete; }
return noneComplete;
This makes use of the fact that each if body contains an unconditional return. If this wasn't the case, you could phrase the construct like so:
if (redStage == 2) {
// redComplete
} else if (blueStage == 2) {
// blueComplete
} else if (greenStage == 2) {
// greenComplete
} else {
// noneComplete
}

playing with java Operators (XOR and AND/OR)

In a program I am trying to check two boolean values (returned from a function); the condition that needs to be checked is:
- only if any one of the returned value is true and the other is false then I have a problem;
- else if both are true or false I am good to go to next step.
Which of the following two examples would be the efficient way to check the condition, or is there a better solution?
a and b are integer values on which I am checking a condition for correctness in isCorrect function and it return true or false.
1.
// checking for the correctness of both a and b
if ((isCorrect(a) && !isCorrect(b)) ||
(!isCorrect(a) && isCorrect(b)))
{
// a OR b is incorrect
}
else
{
// a AND b are both correct or incorrect
}
2.
// checking for the correctness of both a and b
if (! (isCorrect(a) ^ isCorrect(b)))
{
// a OR b is incorrect
}
else
{
// a AND b are correct or incorrect
}
Thanks,
Ivar
P.S: code readability is not an issue.
EDIT: I meant to have an XOR in the second option.
Also, I agree with the == and != options, but what if I had to use boolean operators?
if (isCorrect(a) != isCorrect(b)) {
// a OR b is incorrect
} else {
// a AND b are correct or incorrect
}
Your test doesn't need boolean operators, just this:
if (isCorrect(a) == isCorrect(b)) {
// they both have the same value
} else {
// they don't ...
}
EDIT - I deliberately didn't use the same comments to reflect that the primary purpose of the comment should be to describe the intent, and not the specific implementation. In this case the simplest statement of intent is that both a and b obtained the same result.
simply:
if (isCorrect(a) == isCorrect(b))
{
// a AND b are both correct or incorrect
} else {
// a OR b is incorrect
}
How about this?
if(isCorrect(a) != isCorrect(b))
{
//problem
}
else
{
//not a problem
}
You can use XOR also, but != works fine and is more readable if you are dealing with boolean values, IMO.

Categories