Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
185 views
in Technique[技术] by (71.8m points)

java - How do I validate what I input?

This is what I need to achieve:

The user can try to input a valid license plate. The valid license plate must be in the following format: [XXXX][YYY] Where X is a number between 0 and 9 and Y is an alphabet between A and Z. The user can input word ‘random’ (case insensitive). After that, the program will generate a new random valid license plate.

This is my current code:

for (int i = 0; i < 25; i++) 
    System.out.println("");  
String plat = "";  
do { 
    System.out.print("License Plate Format: XXXXYYY "); 
    plat = scan.nextLine();  
    for (int i = 0; i < plate.size(); i++) {
        if(plat.matches(plate.get(i)))  { 
            System.out.println("not unique!"); 
            scan.nextLine();  plat = " "; break; 
        }  
    } 
while (plat.length() < 7 ); 
plate.add(plat);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use regular expressions for input validation (see here). For this particular task,assuming the plate must have upper case characters, you can match the input with this regular expression to perform validation.

// assuming input is a String and it is already defined
if (input.matches("[0-9]{4}[A-Z]{3}")) {
 return "Plate valid";
} else {
 return "Plate invalid";
}

This regular expression explicitly tells java to look for strings formed by 4 digits followed by 3 characters.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...