да / нет подтверждения ввода, в том числе ввода нет Клавиша ввода - PullRequest
0 голосов
/ 07 сентября 2018

Я пытаюсь перехватить ввод (ключ ввода) и неверный ввод всего, кроме y / n одним способом. Я пробовал это двумя разными способами (вставил), но я не могу заставить работать и «ключ ввода», и «неверный ввод y / n» вместе. Спасибо за вашу помощь.

1-я попытка:

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;
    }

Ответы [ 2 ]

0 голосов
/ 07 сентября 2018

Я пытался с 1-й попытки вашего кода. Я объяснил с комментарием, который включен в код ниже, как;

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;
}
0 голосов
/ 07 сентября 2018

Ваше утверждение 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"))
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...