java - Java:为什么 else 语句总是在我的 while 循环中运行?
问题描述
我在使用 Java 编程时发现了一个问题。自从我搞砸 Java 已经有 6 年了(我一直在做前端设计和开发,从高中开始就不需要用 Java 编程了)。我试图刷新我的想法并进行一些面向对象的编程,但遇到了一个我以前从未见过的问题。
我试图建立一个学校数据库(更具体地说是一个简单的界面),即使我的 if 语句通过,我的 else 语句也总是运行。谁能向我解释为什么即使 if 语句通过 else 语句也会运行?
else {
System.out.println("Bart, come to Principal Skinner's office immediately. You broke the system. \n");
}
直到我将 else 语句更改为 else if 语句(以明确排除那些 if 语句),我才能解决此问题。
else if(!input.equals("1") && !input.equals("2") && !input.equals("3") && !input.equals("4"))
{
System.out.println("Bart, come to Principal Skinner's office immediately. You broke the system. \n");
}
以下是代码:
Scanner scanner = new Scanner(System.in);
int end = 0;
while(end == 0)
{
System.out.println("Welcome to Springfield Elementary School");
System.out.println("----------------------------------------");
System.out.println("Please select from the following options");
System.out.println("1) Add Course");
System.out.println("2) Remove Course");
System.out.println("3) View All Courses");
System.out.println("4) Exit");
System.out.print("-->");
String input = scanner.nextLine();
if(input.equals("1"))
{
System.out.println("That function is currently unavailable at this time");
}
if(input.equals("2"))
{
System.out.println("That function is currently unavailable at this time");
}
if(input.equals("3"))
{
System.out.println("That function is currently unavailable at this time");
}
if(input.equals("4"))
{
end = 1;
System.out.println("Thanks for accessing the Springfield Elementary School Database. Have a nice day.");
}
else {
System.out.println("Bart, come to Principal Skinner's office immediately. You broke the system. \n");
}
}
我对这是否有效并不感兴趣,但为什么 else if 有效而 else 语句无效。这不是为了学校或工作,而是为了纯粹的学习。根据我对 if 语句的理解,如果它们通过了,它们应该跳过所有其他条件语句,除非它是 else if。这似乎与此相矛盾。
为什么我的 else 语句总是在我的 while 循环中运行?
解决方案
if 语句很简单,你遇到的问题也很简单。当你这样做
if(cond1){
code1
}
if(cond2){
code2
}else{
code3
}
它评估,如果 cond1 为真,则运行 cond 1。然后它执行:如果 cond2 为真,则运行 code2,否则(否则)运行 code3。
您将所有 if 语句分开,因此 else 应用的唯一一个是最后一个。你正在寻找的是一个 else-if。
例如
if(cond1){
code1
}else if(cond2){
code2
}else{
code3
}
如果您的所有 if 语句评估为 false,这只会运行最后一个 else 语句。
或者,您可以使用 switch 语句,这些可能更令人困惑,有时更强大,因此我将链接到它并让您阅读它。https://www.w3schools.com/java/java_switch.asp
推荐阅读
- c# - 如何在使用 MOQ 进行模拟时将 Lazy 的类对象类型传递给构造函数
- php - 子目录中的自定义链接('/')重定向到主目录
- php - 在php中用数字和字母实现计数器
- angular - Angular 6 无法获取在显示来自 ngFor 循环数据的数据的输入中键入的新值
- ssl - 运行 Google Cloud Datalab 笔记本时出现 cffi.error.VerificationError(未定义符号:SSLv2_client_method)
- android - 如何为 PIP 功能设置视频 URL 而不是本地视频资源?
- c++ - 从文件中读取直接访问 C++
- javascript - 在数据库中保存多条记录 - 一对多关系
- jquery - 如何删除 jQuery Mobile 导航图标的圆形容器?
- hazelcast - getMap() + 同步地图的后续更改