切换菜单Java
我有一个开关菜单,我希望它循环整个菜单,包括方向,但它只是不断循环我选择的操作。我如何改变它?我从do/while切换到while循环切换菜单Java,java,netbeans,switch-statement,Java,Netbeans,Switch Statement,我有一个开关菜单,我希望它循环整个菜单,包括方向,但它只是不断循环我选择的操作。我如何改变它?我从do/while切换到while循环 int count = 0; String first; String last; String num; Contact person; System.out.println("What would you like to do?"); System.out.println("Type c to creat
int count = 0;
String first;
String last;
String num;
Contact person;
System.out.println("What would you like to do?");
System.out.println("Type c to create");
System.out.println("Tpe e to edit");
System.out.println("Tpe d to delete");
System.out.println("Type q to quit");
Scanner input = new Scanner(System.in);
char choice = input.next().charAt(0);
AddressBook addressBook = new AddressBook();
while ('q' != choice) {
switch (choice) {
case 'c':
System.out.println("Enter first name, last name and phone number");
addressBook.addContact();
count++;
System.out.println("Total number of contact: " + count);
break;
case 'e':
System.out.println("Enter name to be edited");
first = input.next();
last = input.next();
num = null;
person = new Contact(first, last, num);
addressBook.edit(person);
break;
case 'd':
System.out.println("Enter name to be deleted");
first = input.next();
last = input.next();
num = null;
person = new Contact(first, last, num);
addressBook.removeContact(person);
break;
default:
System.out.println("Operation does not exist");
}
}
}
}将
字符选择
初始化为默认字符:
charchoice='a'代码>
然后移动所有这些:
System.out.println("What would you like to do?");
System.out.println("Type c to create");
System.out.println("Tpe e to edit");
System.out.println("Tpe d to delete");
System.out.println("Type q to quit");
choice = input.next().charAt(0);
在while循环中:
while ('q' != choice) {
//show menu options
//allow user to select a menu option
//use switch to operate based on user decision
//once the operation is complete, as long as the user didn't select q,
//the menu options show once more and allow another selection
}
无需使用选项
1.将while('q'!=choice)
更改为while(true)
2.移动到代码下方,同时
System.out.println("What would you like to do?");
System.out.println("Type c to create");
System.out.println("Tpe e to edit");
System.out.println("Tpe d to delete");
System.out.println("Type q to quit");
三,。再加一个箱子
case 'q':
break;
但是(q!=choice)会出现一个错误,因为choice稍后会在code@Sidney,你完全正确。检查我的编辑!一个简单的解决方法是提前声明choice
,将其初始化为默认值,然后允许其被覆盖。是的,这是一个很好的方法。绝对干净。我不确定OP在他们的教案中的位置,所以我采用了最直接的建议:)额外变量意味着额外内存:)