我知道这是非常简单的事情,但是,我只编程了几个月,所以我的大脑有时会变得模糊,并且我需要使用嵌套 else if 语句的 while 循环的帮助。我的循环的问题是连续的,因为用户永远没有机会输入他们的选择(-1 停止循环)。如何更改循环,使其通过要求用户输入选择(1-4 或 -1 退出)来运行
请提供任何帮助。我知道这很简单,我已经搜索过以前的论坛讨论,但我似乎无法使其发挥作用。
//create new scanner object
Scanner userInput = new Scanner (System.in);
int end = 0;
//find out what user wants to do with address book
while (end != -1)
{
System.out.println(" ");
System.out.println(" ");
System.out.println("----------------------------");
System.out.println("What would you like to do with your address book? ...");
System.out.println("----------------------------");
System.out.println("Add new [Enter 1]");
System.out.println("Delete existing [Enter 2]");
System.out.println("Edit existing [Enter 3]");
System.out.println("Search for [Enter 4]");
System.out.println("EXIT [Enter -1]");
}
if (userInput.hasNext() && (userInput.nextInt() == 1))
{
AddressBookProcessor.addContact();
}
else if (userInput.hasNext() && userInput.nextInt() == 2)
{
AddressBookProcessor.deleteContact();
}
else if (userInput.hasNext() && userInput.nextInt() == 3)
{
AddressBookProcessor.editContact();
}
else if (userInput.hasNext() && userInput.nextInt() == 4)
{
AddressBookProcessor.findContact();
}
else if (userInput.nextInt() != 1 || userInput.nextInt() != 2
|| userInput.nextInt() != 3 || userInput.nextInt() != -1)
{
System.out.println("Please enter a valid input");
end = -1;
}
}
最佳答案
将 if/else 移至 while 循环内。
关于java循环,如果否则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15489511/