y/n 输入验证,包括无输入 Enter 键

我试图在一种方法中捕获没有输入(输入键)和无效输入除 y/n 之外的所有内容。我尝试了两种不同的方式(粘贴),但我无法同时使用“输入键”和“错误输入 y/n”。感谢您的帮助。


第一次尝试:


public static String askToContinue(Scanner sc) {


String choice = "";

boolean isValid = false;


while (!isValid){System.out.print("Continue? (y/n): ");

    if (sc.hasNext()){

        choice = sc.next();

        isValid = true;

    } else {System.out.println("Error! "

                + "This entry is required. Try again");    

    }


    if (isValid && !choice.equals("y") || !choice.equals("n")) {

        System.out.println("Error! Entry must be 'y' or 'n'. Try again");

        isValid = false;

    }

   }

    //sc.nextLine();  // discard any other data entered on the line

    System.out.println();

    return choice;

   }        




   2nd attempt


    public static String askToContinue(Scanner sc) {

    System.out.print("Continue? (y/n): ");

    String choice;




    while (true) {choice = sc.next();


    //?????????????????????????????????????????????????????

        if (choice.length() == 0){ System.out.println("Error! "

                + "This entry is required. Try again");

            continue;

        }



        if (!(choice.equals("y") || choice.equals("n"))) {

            System.out.println("Error! Entry must be 'y' or 'n'. Try                   again");

            continue;

        }


        break;    

    }


    sc.nextLine();  // discard any other data entered on the line

    System.out.println();

    return choice;

    }


慕标琳琳
浏览 129回答 2
2回答

梵蒂冈之花

我尝试了您的代码的第一次尝试。我用注释行进行了解释,注释行包含在下面的代码中,例如;public static String askToContinue(Scanner sc) {    String choice = "";    boolean isValid = false;    while (!isValid) {        System.out.print("Continue? (y/n): ");        choice = sc.nextLine(); //to reads all line , because this cannot read with empty enter input        isValid = true;        if (choice.isEmpty()) {  //this isEmpty for empty enter            System.out.println("Error! "                    + "This entry is required. Try again");        }        System.out.println(choice);        //this logic if not y or n , it will return error        if (!choice.equals("y") && !choice.equals("n")) {            System.out.println("Error! Entry must be 'y' or 'n'. Try again");            isValid = false;        }    }    //sc.nextLine();  // discard any other data entered on the line    System.out.println();    return choice;}

繁星淼淼

您在第一种情况下的 if 语句是错误的。您正在检查是否选择is not equal to 'y' 或 not equal to 'n'将始终为真。改变if (isValid && !choice.equals("y") || !choice.equals("n"))到if (isValid && !choice.equals("y") && !choice.equals("n"))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java