我有一个切换菜单,我希望它循环整个菜单,包括方向,但它只是循环我选择的操作。我该如何改变它?我从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 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");
}
}
}
}
答案 0 :(得分:2)
将char choice
初始化为默认字符:
char choice = '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 :(得分:1)
无需使用choice
。
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");
3。添加一个额外的案例
case 'q':
break;