jeudi 6 septembre 2018

y/n input validation including no input Enter key

I am trying to catch no input (enter key) and invalid input everything but y/n in one method. I tried it two different ways (pasted) but I cannot make work both “enter key” and “mistype y/n” together. Thank you for your help.

1st attempt:

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

Aucun commentaire:

Enregistrer un commentaire