I'm tring to do some Java coding with NETBEANS 7.1.2, but it gives me the error " 'else' without 'if' " when I try to build this code:
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String search1;
search1 = jTextField1.getText();
// stone
if (search1=="Stone" || search1=="Rock" || search1=="stone" || search1=="rock" || search1=="1");
{
jTextField2.setText("Stone: 1");
}
// grass
else if (search1=="Grass" || search1=="grass");
{
jTextField2.setText("Grass: 2");
}
}
The problem occurs at the 'else if' under the //grass. Am I doing something wrong?
In this line:
if (search1=="Stone" || search1=="Rock" || search1=="stone" || search1=="rock" || search1=="1");
And this line:
else if (search1=="Grass" || search1=="grass");
You must remove the ; at the end. Those semicolons are misplaced, the compiler will interpret the first if statement as an if without a body, the code between the {} as a block scope and the else if statement as an else without an if.
Also, be aware that all the string comparisons are mistaken, in Java you must use equals() for comparing two strings for equality, not ==, which compares for identity.
You have an ";" after the first condition.
The compiler assume this is the end of if statement, therefore the compiler show error at "else if" line. Remove the ";" and it should be fine!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With