我有一个while循环,它不起作用。正如您在我的代码中看到的那样,如果变量“choice”不等于p或n,则应该循环。即使我选择等于p或n,它至少循环一次。我有不好的位置或什么?
do{
System.out.println("Enter the name of the contact you would like to update");
name = sc.nextLine();
System.out.println("Would you like to update their name(press n) or phone"
+ "number(press p)?");
choice = sc.nextLine();
if(choice.equalsIgnoreCase("n")){
System.out.println("Enter the new name for the contact");
String name1 = sc.nextLine();
SQL.updateName(name, name1);
c = SQL.searchByName(name1);
if(c != null)
System.out.printf("Name: %s\t Phonenumber: %s\n", c.getName(), c.getPhone());
else
System.out.println(name+" does not exist");
}
else if(choice.equalsIgnoreCase("p")){
System.out.println("Enter the new number for "+name);
phone = sc.nextLine();
SQL.updateNumber(name, phone);
c = SQL.searchByPhone(phone);
if(c != null)
System.out.printf("Name: %s\t Phonenumber: %s\n", c.getName(), c.getPhone());
else
System.out.println(name+" does not exist");
}
}
while(choice.equalsIgnoreCase("p") == false || choice.equalsIgnoreCase("n") == false);
答案 0 :(得分:4)
你的逻辑错误;任何choice
始终不等于"p"
或不等于"n"
。只有当它不是"p"
并且不是"n"
时才想循环。使用&&
:
while(choice.equalsIgnoreCase("p") == false && choice.equalsIgnoreCase("n") == false);