java - 验证 if 语句不能正常工作

标签 java string validation if-statement

我正在尝试制作一个 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”,它会再次运行,如果是其他任何内容,它会关闭,而不是再次询问有效输入。

最佳答案

您的条件不起作用,因为 if 语句后有 ;

if( !choice.equalsIgnoreCase("y") && !choice.equalsIgnoreCase("n") );
                                                                    ^^

改变

if( !choice.equalsIgnoreCase("y") && !choice.equalsIgnoreCase("n") );
     {
         System.out.println("Invalid input try again");
         continue;
     }

if(!(choice.equalsIgnoreCase("y") || choice.equalsIgnoreCase("n")))
     {
         System.out.println("Invalid input try again");
         continue;
     }

关于java - 验证 if 语句不能正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15425862/

相关文章:

java - 如果只有一个编写器线程,我们是否需要同步 java HashMap gets

java - Java中二叉树的元素求和

python - Python中的“就地”字符串修改

PHP 对象验证

Javascript/jQuery 表单验证

php - Tinymce 和 javascript - PHP 验证

java - 拖放功能在 selenium Webdriver 中不起作用

java - 向 JList 添加多个元素

c - 将 2d 字符数组附加到 1d 字符数组(在 C 中)

c++ - 我如何在 C++ 中的 for 循环之外保存一个字符串