我正在尝试创建一个 if 语句来捕获程序的用户是否输入了除 y 或 n 之外的值,以解决程序“继续?(y/n):”末尾提出的问题。但无论我输入什么值“y”、“n”或无效的值,我都会从控制台收到消息“无效输入再试一次”。这只应该在选择不是 y 或 n 时发生,任何人都知道为什么不管我输入什么它都会继续发生?
import java.util.Scanner;
public class ProductApp
{
public static void main(String[] args)
{
//display a welcome message
System.out.println("Welcome to the Product Selector ");
System.out.println();
// perform 1 or more selections
Scanner sc = new Scanner(System.in);
String choice = "y";
while (choice.equalsIgnoreCase("y"))
{
System.out.println("Enter Product Code: ");
String productCode = sc.next(); //read the product code
sc.nextLine() ; //discard any other data entered on the line
//make sure the case the user enters for a product code doesn't matter
productCode = productCode.toLowerCase();
// get the Product object
Product p = ProductDB.getProduct(productCode) ;
// display the output
System.out.println();
if (p != null)
System.out.println(p);
else
System.out.println("No product matches this product code. \n");
System.out.println("Product count: " + Product.getCount() + "\n" );
// see if the user wants to continue
System.out.println("Continue? (y/n): ");
choice = sc.nextLine() ;
System.out.println();
if( !choice.equalsIgnoreCase("y") && !choice.equalsIgnoreCase("n") );
{
System.out.println("Invalid input try again");
continue;
}
}
}
}
同样,无论我在哪里收到“无效输入再试一次”消息,程序都会要求输入一次新输入,然后继续输入是否有效。如果它是“y”,它会再次运行,如果它有其他任何东西,它就会关闭,而不是第二次询问有效输入。