首页 > 解决方案 > 为什么我的 else 语句会留下错误?

问题描述

嗨,我是 java 的初学者,我只想知道为什么我会收到 else 的错误消息('else without 'if')。

public class Exercise6 {
    public static void main(String[] args) {
    String user = Input.askString("Username:");
    String pass = Input.askString("Password:");
    if (user.equals("joe") || pass.equals("guess"));
    {
        System.out.println("Welcome, joe!");
        } 
            else
        {
            System.out.println("Incorrect username or password.");    


    }
}
}

标签: java

解决方案


在查看您的代码问题后,If 语句后是或分号(;)。在那什么中,if 语句将在那里结束,所以 else 将被单独忽略。所以正确的一个在这里:

public class Exercise6 {
    public static void main(String[] args) {
    String user = Input.askString("Username:");
    String pass = Input.askString("Password:");
    if (user.equals("joe") || pass.equals("guess"))
    {
        System.out.println("Welcome, joe!");
        } 
        else
        {
            System.out.println("Incorrect username or password.");    
        }
    }
}

你也可以这样做;

public class Exercise6 {
    public static void main(String[] args) {
    String user = Input.askString("Username:");
    String pass = Input.askString("Password:");
    if (user.equals("joe") || pass.equals("guess"))
        System.out.println("Welcome, joe!");
     else
        System.out.println("Incorrect username or password.");    
    }
}

这是因为如果 if 或 else 部分中有单个语句,则不需要大括号.. 我希望你有想法。


推荐阅读