尝试验证用户是否输入了 Yes 或 No

Trying to validate whether or not the user typed in Yes or No

所以我试图验证用户输入的是“是”还是“否”,并继续询问,直到他们输入一个或另一个。到目前为止,这是我的代码。

System.out.println("Would you like a Diamond instead of a Pyramid? Type Yes or No");        
String input2 = scan.nextLine();
boolean d = input2.equals("Yes");
System.out.println(d);

while ((d != false) ||  (d != true)) {
    System.out.println("Invalid Input. Please try again");
    input2 = scan.nextLine();
    d = input2.equals("Yes");
    System.out.println(d);
}

我哪里错了?我是 java 的新手。任何帮助将不胜感激。

编辑:我的写作很糟糕。我要的是这种逻辑。 询问用户是否想要钻石而不是金字塔。 一种。用户必须键入“是”或“否”。 b.如果用户没有键入这些,请再次询问,直到他们提供适当的输入。

您将在

处陷入无限循环
while ((d != false) ||  (d != true))

因为 dboolean,即使更新后也会是 truefalse,并且在这两种情况下都满足上述条件。相反,您可以将其更改为

System.out.println("Would you like a Diamond instead of a Pyramid? Type Yes or No");        
String input2 = scan.nextLine();
boolean d = input2.equalsIgnoreCase("Yes") || input.equalsIgnoreCase("No"); // confirms if the user input is Yes/No or invalid other than that
.... 
while (!d) { // d==false ' invalid user input
    System.out.println("Invalid Input. Please try again");
    input2 = scan.nextLine();
    d = input2.equalsIgnoreCase("Yes") || input.equalsIgnoreCase("No");
    System.out.println(d); 
    // also printing a boolean would print either true or false base on your input; you migt want to perform some other action
} // this would exit on user input "Yes"

布尔值只能等同于 true 或 false,因此无论发生什么情况,您的 while 循环都会执行,因为 d 为真或为假。我想你只想做

while (d != true)

每当用户键入您的条件之一为假而另一个为真时,您就在您的条件中使用 or(||) 运算符,这就是它无法正常工作的原因。 如果您想停止询问真实价值,请写下条件。

while(d != true)