java - 为什么我的 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.");
}
}
}
解决方案
在查看您的代码问题后,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 部分中有单个语句,则不需要大括号.. 我希望你有想法。
推荐阅读
- laravel - Laravel 水平管理器在水平:: 终止并运行伪造守护程序后不会重新启动
- react-native - 如何将道具传递给 createBottomTabNavigator 的所有选项卡
- asp.net - 全屏网页上的 ASP NET 滚动条?
- r - 通过 openxlsx 或 googlesheets 将公式作为文本粘贴到单元格中
- android - 为什么广播接收器没有检测到 WIFI_P2P_CONNECTION_CHANGED_ACTION?
- java - Java Rest Assured 如何从 Microsoft oAuth2 获取令牌
- c - sizeof(bool) 的改变真的能打破旧代码吗?
- angular - 模板语句和事件处理程序有什么区别?
- package - 我可以为不同的环境使用不同版本的包吗?
- python - 将 pandas DataFrames 与 NaN 合并以查找缺失的行