Reputation: 21
Learning Java, now I do not know why but this code keeps giving me issues with else if
statements.
public class Sherlock
{
public static void main(String[] args)
{
String answer = "Watson";
String response = "";
int tries = 0;
Scanner input = new Scanner(System.in);
while (tries <=3);
{
System.out.print("Enter the name of Sherlock's partner, and dear friend. ");
response = input.nextLine();
tries++;
if (response.equals ("Watson"))
while (tries<= 3)
{
System.out.println("Yes, that is right, Barrel Rider.");
break;
}
else if (tries == 3)
{
System.out.println("Ooooh, sorry kid but it looks like you are S.O.L.");
break;
}
else
while (tries <= 3)
{
System.out.println("Sorry, try again!");
}
}
}
}
The if else statement error has been more or less solved, but now I'm getting a different error:
Sherlock.java:24: error: break outside switch or loop break; ^ 1 error
Why does it keep insisting I put break outside the switch or loop?
Upvotes: 0
Views: 180
Reputation: 5647
remove the semi-colons from the if statement
if (response.equals ("Watson"))
And the while loop
while (tries <=3)
These semi-colons are messing up the parsing of your control statements. The reason why the semi-colon after the if-statement messes things up is that the parser doesn't expect there to be a body due to the presence of the semi-colon, and therefore it doesn't expect there to be an else statement after an if-statement with no body.
In the future, I suggest that you make sure that you have checked your code for valid semantics and syntax. You will learn the basics about control statements from any good tutorial on YouTube.
Upvotes: 1