我有一个 do 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);
最佳答案
你的逻辑不正确;任何选择
将始终不等于“p”
或不等于“n”
。仅当它不是 "p"
且 不是 "n"
时才需要循环。使用&&
:
while(choice.equalsIgnoreCase("p") == false && choice.equalsIgnoreCase("n") == false);
关于java - do while 循环在我不希望它循环时循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25923229/