gpt4 book ai didi

java - 为什么我的 else 语句会留下错误?

转载 作者:行者123 更新时间:2023-12-02 09:54:40 25 4
gpt4 key购买 nike

嗨,我是 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.");


}
}
}

最佳答案

查看代码后问题是 If 语句后的或分号(;)。其中,what、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 部分中有单个语句,则不需要大括号..我希望你已经知道了。

关于java - 为什么我的 else 语句会留下错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56087075/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com