Home > Back-end >  Else Statement not working [Ecplise IDE Java]
Else Statement not working [Ecplise IDE Java]

Time:09-17

I wrote this script but the Else statement wont work.

Exception in thread "main" java.lang.Error: Unresolved compilation problem: Syntax error on token "else", delete this token

import java.util.Scanner;
public class Question4 {

    public static void main(String[] args) 
    {
    Scanner input = new Scanner(System.in);
    System.out.println("Welcome to the secret secret and secure notepad!");
    System.out.println("What is your name?");
    String name = input.next();
    System.out.println("Please enter a password:"); 
    String password = input.next();
    System.out.println("Please confirm password: ");
    String confirmpassword = input.next(); 
    
    
    if (password == (confirmpassword))
        
        System.out.println("Your password has been set. Now entering your Notepad!");
        System.out.println("Here are your notes");
    else
        
        System.out.println("Passwords do not match! Error Code 1");```

CodePudding user response:

If you want to execute more than a single line of code during an if else statement in Java, you should throw in curly braces after the conditional of each statement. I have found that doing so also helps with code readability when I am keeping track of where the block of code that is effected by the conditional ends.

For example,

if(password == (confirmpassword)){
        
        System.out.println("Your password has been set. Now entering your Notepad!");
        System.out.println("Here are your notes");
} else {
        
        System.out.println("Passwords do not match! Error Code 1");
}

CodePudding user response:

if (x==1)

System.out.print(x);

else

System.out.print(x);

After if else statement , without using braces only one statement can be executed.

If we write more than one statement after if else without using braces , it is not considered inside if else.

For example:-

if (x==1)

System.out.print(x);

System.out.print(5);

In the above example , second statement is considered outside of if .

  • Related