Syntax error, delete token "else" - java

public class Basic {
public static void main (String []args){
int first = 1;
if (first == 1);{
System.out.println("I did it");
}
else {
System.out.println("I didnt do it");
}
I dont know what to do, is there a mistake and i followed all the steps in the tutorials i'm watching. It just says delete the token

Remove the semi-colon after (first == 1)

Remove the semicolon after if (first == 1);
The semicolon after makes the if statement finished and the block after {} is not a part of if.So the else part is complaing about the non-existence of if because else cannot exist without if

You should delete the obviously misplaced ; and finish all your opened brackets. Try this:
public class Basic
{
public static void main (String []args)
{
int first = 1;
if (first == 1)
{
System.out.println("I did it");
}
else
{
System.out.println("I didnt do it");
}
}
}
If you have problems with brackets, you can configure Eclipse to automatically put closed bracket under each other like in the example.
The semicolon you have placed there ended your if statement, so it had no effect on the code between the brackets. You can imagine (Java purists will pardon the simple explanation), that after if, there is only one command or command block allowed. The brackets will group more commands to one block.
Try this example, it will explain you how it works.
int i=1;
if (i==1)
System.out.println("I should be here when i==1");
else
System.out.println("Will this output be printed out? No, this is else section!");
if (i==2)
{
System.out.println("I should be here when i==2");
System.out.println("Will this output be printed out? No! Condition was not met, because i==1 and we are in the block");
}
if (i==2)
System.out.println("I should be here when i==2");
System.out.println("Will this output be printed out? Yes, because the commands are not in the block!");
if (i==2); //WATCH OUT, there is semicolon that terminated if statement
System.out.println("Will this output be printed out? Yes, because that semicolon has terminated the if statement!");

Related

Java recursion method returns wrong value

I have a bit of a problem with this recursion method. I'm fairly new to Java.
This method checks if an input is either "exit" only or "start" followed by two times either "user" or "easy".
It works fine except for the return. If I enter a wrong input and then a right on it returns the previous wrong input with which I obviously can't continue working, why is that?
I've had this problem before but always somehow managed to avoid it.
You might notice that I print out a valid commadnd right when it's validated, this works fine and produces the result I need. But when printing out the return of the function on line 2 the above mentioned problem takes place. I've added numbers to the printed strings so I can recognize which is which.
I have tried returning immediately when there's a valid command but I still need that retrun at the end since the function gives me an error if return statements are exclusively in conditional statements so the problem persists.
Thanks for any help!
public static void main(String[] args) {
System.out.println(setup() + "3");
}
static String setup() {
System.out.print("Input command: ");
String command = input.nextLine();
String[] split = command.split(" ");
if(!(command.equals("exit") || split.length == 3)) {
System.out.println("Invalid parameters!");
setup();
}
else {
if(command.equals("exit")) {
System.out.println("Valid parameters! Exit");
System.out.println(command + "2");
}
else if(split[0].equals("start") && (split[1].equals("easy") || (split[1].equals("user")) && split[2].equals("easy") || split[2].equals("user"))) {
System.out.println("Valid parameters! Start");
System.out.println(command + "1");
}
else {
System.out.println("Invalid parameters!");
setup();
}
}
return command;
}
first of all I think that you meant to call the recusive call as
return setup()
second of all when using conditional operator (&&, ||) you should use () for make sure you get the logic condition you expect.
if you will update it to :
return setup instead of setup()
validate what you wrap the right part of condition with Parenthesis():
else if (split[0].equals("start") && ((split[1].equals("easy") || split[1].equals("user")) && (split[2].equals("easy") || split[2].equals("user")))) { System.out.println("Valid parameters! Start"); System.out.println(command + "1"); }

Struggling with compare last 2/3/4 characters Java (repl.it 018 - Conditional Statement Practice 4)

Dear Stackoverflow community I am Struggling with one task on repl.it (018) Conditional Statements 4
So they want me to do that :
Instructions from your teacher:
For you to do:
Given a string variable "word", do the following tests
If the word ends in "y", print "-ies"
If the word ends in "ey", print "-eys"
If the word ends in "ife", print "-ives"
If none of the above is true, print "-s"
No more than one should be printed.
and my code looks like this :
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
System.out.print("In:");
String word = inp.nextLine();
//DO NOT CHANGE ABOVE CODE! Write your code below
if(word.endsWith("y"){
System.out.println("-ies");
}
else if(word.endsWith("ey")){
System.out.println("-eys");
}
else if(word.endsWith("ife")){
System.out.println("-ives");
}
else{
System.out.println("-s");
}
}
}
When I run it for example my input is :Hey
and of course my code will go through the code and see if the first statement is correct and yes it is equal because y = y at the end and that is WRONG!
My question is how can i let my code compare the last 2 or 3 characters so it will print out the right value when I input Hey.
If I input Hey it should print out :
-eys and not -ies
Ty
Since ending with "ey" is a subset of ending with "y", your 2nd if will never be true.
Change the order of your tests to the most specific first:
if(word.endsWith("ey"){
System.out.println("-eys");
}
else if(word.endsWith("y")){
System.out.println("-ies");
}
else if(word.endsWith("ife")){
System.out.println("-ives");
}
reorder the conditions as such:
if(word.endsWith("ey")){
System.out.println("-eys");
}
else if(word.endsWith("ife")){
System.out.println("-ives");
}
else if(word.endsWith("y")){
System.out.println("-ies");
}
else{
System.out.println("-s");
}
This means we hoist the condition that is most specific and put the less specific ones below.
I've put the else if(word.endsWith("y")) as the last of the else ifs but it really doesn't matter where within the else if chaining you put it as long as it's before the condition if(word.endsWith("ey")) things should be fine.

Java closing statements

Okay so my code works, however if the user correctly guesses "blue", the line prints "you got the right color!". Then the code should end. However, it brings up another a k.next(); line. How can I prevent this?
If you do not understand, here is the code.
import java.util.Scanner;
public class BEassignment11
{
public static void main (String [] args)
{
Scanner k = new Scanner (System.in);
String color;
String again;
do
{
System.out.println ("Try to guess my favorite color!");
color = k.next();
if (color.equalsIgnoreCase ("blue"))
{
System.out.println ("You got the right color!");
}
else
System.out.println ("That is not the right color. Would you like to try again? Yes/No");
again = k.next();
}
while (again.equalsIgnoreCase ("yes"));
}
}
You can just break out of the loop with the "break" statement like this:
if (color.equalsIgnoreCase ("blue")){
System.out.println ("You got the right color!");
break;
}
You can use break following System.out.println ("You got the right color!"); within if statement at do..while loop.
Or define a variable before do..while loop, for example var boolFlag = false set variable to true within if statement boolFlag = true, include || boolFlag === true within while condition.
System.out.println.... is part of the else clause. You seem to be surprised that the line
again = k.next();
still gets executed even when the user gets the color correct. I suggest you change the else code to the following:
if (color.equalsIgnoreCase ("blue"))
{
System.out.println ("You got the right color!");
again = "No";
}
else
{
System.out.println ("That is not the right color. Would you like to try again? Yes/No");
again = k.next();
}
That will automatically tell the program not to run again if the user guesses correctly and will only read the user's answer for trying again if they answer incorrectly.

Returning back to the beginning of a loop using "continue" on Java

public void talk() {
String[] prompts = {"Describe to me in a sentence why this is a cool program.",
"Describe to me in a sentence how your day was.",
"Describe to me in a sentence what programming means to you.",
"Describe to me in a sentence why food is neccessary for humans."};
iramInLoop = true;
while(iramInLoop)
{
int i = new Random().nextInt(prompts.length);
System.out.println(prompts[i]);
String input = Raybot.getInput();
if(!checkPunc(input) && !checkCaps(input)){
System.out.println("Check your capitalization and your punctuation!");
}
else{
System.out.println("Great grammar keep it up! Do you want to try again?");
if(input.equals("yes")) continue;
else
{
iramInLoop = false;
Raybot.talkForever();//this exits the loop
}
}
}
}
I am having extreme trouble trying to restart my loop. So at the end of my code when the loop is done running I put a string which asks if the user wants to try again and if the user says yes I want it to go back to the beginning of the loop and do what the loop does again. However, every time I run it it goes to the end of the loop and doesn't even ask for an input.
I think you should be breaking out of the loop if the person guessed right, but then decided not to continue. In this case, your logic should be something like this:
while (true) {
int i = new Random().nextInt(prompts.length);
System.out.println(prompts[i]);
String input = Raybot.getInput();
if (!checkPunc(input) && !checkCaps(input)) {
System.out.println("Check your capitalization and your punctuation!");
}
else {
System.out.println("Great grammar keep it up! Do you want to try again?");
input = Raybot.getInput();
if (input.equals("no")) {
break;
}
}
}
// whatever this does, you intended for it happen after the loop terminates, so do it here
Raybot.talkForever();
You are missing to actually accept any input
maybe
System.out.println("Great grammar keep it up! Do you want to try again?");
input = Raybot.getInput();
change if(input.equals("yes")) continue;
to if(Raybot.getInput().equals("yes")) continue;

Okay, still having trouble with else if method in Java

import java.util.Scanner;
public class SherlockHolmes {
String answer = "Watson";
String response = " ";
int tries = 0;
int tries = 3;
Scanner input = new Scanner(System.in); {
System.out.print("Enter the name of Sherlock's partner, and dear friend.");
response = input.nextLine();
tries++;
if (response.equals("Watson"))
else
while (tries <= 3)
System.out.print("Ooooh, sorry kid! Try again!"); {
System.out.println("Yes, that's right, Barrel Rider.");
break;
} else if (tries == 3) {
System.out.println("Ooooo, sorry kid. But, it looks like you're S.O.L!");
break;
}
}
}
My biggest question is why I'm getting two errors with this method, the error
being: SherlockHolmes.java:16: error: 'else' without 'if'
else
^
SherlockHolmes.java:24: error: 'else' without 'if'
else if(tries == 3)
^
2 errors
I put if code in every line, yet its telling me : "Else without if" for both entries of "else". I am kind of frustrated, and I don't slagging get how Java thinks I have no if when it is clearly there!
What am I doing wrong that Java thinks I have no if code fashioned in?
If you want an if statement with an empty body, you NEED curly braces in Java. Honestly, you should just have way more braces in your code. I strongly suggest reading up on Java coding conventions http://www.oracle.com/technetwork/java/codeconventions-150003.pdf
Example:
if (response.equals("Watson"))
else while (tries <= 3)
For that empty if to compile, you need:
if (response.equals("Watson")) {
}
else while (tries <= 3) {
// loop body
}
You have many syntax errors.
First, you cannot attach an else-if to a while block. Second, if you're trying to make it so that if the response does not equal "Watson", then use the "not equal to" operator, which is simply "!" (an exclamation mark).
Control flow is made up of
if (condition) {} Must be used once, and must be first
else if (condition) {} as many times as you want, optional, must be in between else and if if included
else {} optional, must be last and used once if included
Curly braces and order are mandatory. In Java, it is best practice, and usually required to put curly braces around all blocks: if, while, for. Another thing you need to know is that while loops are not the same as conditionals. They can't be attached to else or else if statements. So your while loop needs to change to
while (tries <= 3) {
...
}
Do this similarly with the conditional statements.
System.out.print("Enter the name of Sherlock's partner, and dear friend.");
response = input.nextLine();
tries++;
while (tries <= 3) {
if (response.equals("Watson")) {
System.out.println("Yes, that's right, Barrel Rider.");
}
else {
System.out.print("Ooooh, sorry kid! Try again!");
break;
}
if (tries == 3) { // If the while loop finishes
System.out.println("Ooooo, sorry kid. But, it looks like you're S.O.L!");
break;
}

Categories

Resources