Search code examples
javabufferedreader

Bufferedreader validation check errors


I am pretty sure that I had this code working and then for some reason today I haven't changed anything and it isn't working properly. I only get it to work when I enter 1 character, otherwise it fails one of the checks.

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));   

System.out.println("Enter your 1-12 capitalized alphanumeric character DLN: ");

String DLN = null;
DLN = br.readLine();                                                            

    if(DLN == null || DLN.length() > 12 || DLN.length() < 1 || !DLN.matches("[A-Z0-9]")) {      
       System.out.println("You have not entered a 1-12 character DLN");
       return;
    }

Solution

  • Your current regex pattern only allows one character. Try this instead:

    !DLN.matches("[A-Z0-9]+")
    // ...................^
    

    Or better, express your length requirements as part of the regex:

    if(DLN == null || !DLN.matches("[A-Z0-9]{1,12}")) {      
       System.out.println("You have not entered a 1-12 character DLN");
       return;
    }