我正在尝试运行一个 do...while 条件不满足,但出于某种原因,无论条件值如何,我的代码每次都会循环。我已经检查了我的调试器,变量的值是正确的,并且根据类似的逻辑满足循环内的条件。出于某种原因,!
不起作用。这是我的代码
do
{
if(isRaceHorse.equalsIgnoreCase("Y"))
{
System.out.print("Please enter the number of races your horse has been in >> ");
numRaces = input.nextInt();
input.nextLine();
System.out.println("Your horse is named " + name + " it is a " + color + " horse born in " + birthYear + " and it has been in " + numRaces + " races.");
}
else if(isRaceHorse.equalsIgnoreCase("N"))
{
System.out.println("Your horse is named " + name + " it is a " + color + " horse born in " + birthYear + ".");
}
else
{
System.out.println("Please use Y for yes and N for no.");
System.out.print("Is your horse a race horse? Enter Y for yes and N for no >> ");
isRaceHorse = input.nextLine();
}
}while(!(isRaceHorse.equalsIgnoreCase("y")) || !(isRaceHorse.equalsIgnoreCase("n")));
有人知道为什么这没有给我我想要的东西吗?
最佳答案
!(isRaceHorse.equalsIgnoreCase("y")) || !(isRaceHorse.equalsIgnoreCase("n"))
在英语中,这意味着只要 isRaceHorse
不等于 "y"
或 isRaceHorse<,循环就会继续
不等于 "n"
。因为它不能同时等于 "y"
和 "n"
,我很确定你想使用 &&
相反:
!isRaceHorse.equalsIgnoreCase("y") && !isRaceHorse.equalsIgnoreCase("n")
关于java - 否定不适用于 .equalsIgnoreCase(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49723553/