[英]code not executing within switch statement
我可能缺少一些非常简单的东西,但是我是新手,寻求帮助会更容易。 这是家庭作业,因此您可以根据需要提供线索,但是请理解我在Java方面很糟糕。
下面是地址簿的一些代码。 我希望用户输入1来查看条目2以便将另一个条目放入书中或3退出。 我使该程序正常工作,但没有循环询问用户下一步该怎么做。 然后,我编写了一条switch语句,当用户选择1时,程序不会运行与情况1相关的代码,并且与情况2相同。该程序确实验证了我的输入(我在单独的类中编写了一个验证器)
编码时我错过了什么吗?
我又是新来的,所以别打我。
import java.util.Scanner;
public class AddressBookEntryApp
{
public static void main(String[] args)
{
//create new scanner
Scanner ip = new Scanner(System.in);
//welcome user to the address book application
System.out.println("Welcome to the Address Book Application");
System.out.println();
int choice = 0;
boolean quit = false;
do
{
//have the user enter a menu number
System.out.println("1 - List entires");
System.out.println("2 - Add entry");
System.out.println("3 - Exit");
System.out.println();
int menuNumber = Validator.getInt(ip, "Enter menu number: ", 1, 3);
System.out.println();
switch (choice)
{
case 1:
AddressBookIO GetEntryObject = new AddressBookIO();
GetEntryObject.getEntriesString();
System.out.println(AddressBookIO.getEntriesString());
break;
case 2:
String name = Validator.getEntry(ip, "Enter name: ");
String email = Validator.getEntry(ip, "Enter email address");
String phone = Validator.getEntry(ip, "Enter phone number: ");
AddressBookEntry newEntry = new AddressBookEntry(name, email, phone);
AddressBookIO.saveEntry(newEntry);
break;
}
}while (!quit);
}
}
choice
设置为0
。 您是要打开menuNumber
吗?
您为选择分配0( int choice = 0;
),并且永远不会更改它,因此在开关中它既不匹配1也不匹配2。
应该是
switch (menuNumber)
是的,您menuNumber
Validator的输出分配给menuNumber
,但是您正在choice
上进行switch
。
您不更改变量choice
的值。 因此,它一开始就保持为“ 0”。 因此,您的代码永远不会进入case语句。 那就是问题所在 。 请尝试以下操作:
choice = Validator.getInt(ip, "Enter menu number: ", 1, 3);
这行不应该
int menuNumber = Validator.getInt(ip, "Enter menu number: ", 1, 3);
转换为以下内容:
choice = Validator.getInt(ip, "Enter menu number: ", 1, 3);
如前所述,“选择”变量不是用户的输入(我想是“ menuNumber”)。 这是第一个问题。
现在的问题是:您为什么会犯这个错误? 因为您的代码太复杂。 如果您阅读Martin Fowler的“清洁代码”或其他文章中的建议,则可以编写出更好的代码。 两个简单提示:
最重要的是破产,学习使用调试器,并立即发现该错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.