プログラムの最後に尋ねられる質問「続行しますか? (y/n):」に対して、プログラムのユーザーが y または n 以外の値を入力したかどうかをキャッチする if ステートメントを作成しようとしています。しかし、「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」の場合は再度実行され、それ以外の場合は有効な入力を再度要求する代わりに終了します。