문제

I'm trying to write a small program that reads in a license plate number from the user and returns if it is valid or not. I'm not quite sure on how to loop through it to see if certain characters are correct.

Note: This is suppose to be an Icelandic license number plate.

With Icelandic license number plates, the first 2 characters are capital strings. the 3rd character can be either a capital letter or a number, and the last 2 must be numbers as well. Here is an example of a valid license plate: "HX567".

Anyway, here's my code so far, hopefully someone here can show me how to loop through the string and check if the first 2 characters are letters and capital etc.....

import java.util.Scanner;
import java.util.*;

public class Bilnumer {

    public static void main(String[] args) {
        Scanner skanni = new Scanner(System.in);

        System.out.println("Good day, please enter your license plate number.");
        System.out.println("License plate number: ");
        String bilnumer = skanni.nextLine();

        bilnumer = bilnumer.toUpperCase();

        int lengd = bilnumer.length();

        if (lengd > 5)
        {
            System.out.println("License plate numbers can not be more then 5 characters");
        }else{
            System.out.println("Your license plate number is: "+bilnumer);
        }


    }

}
도움이 되었습니까?

해결책

You could use a regular expression:

Matcher m = Pattern.compile("[A-Z][A-Z]([A-Z]|\\d)\\d\\d").matcher(bilnumer);
if (m.find()) {
    System.out.println(bilnumer + " is a valid number plate");
} else {
    System.out.println(bilnumer + " is not a valid number plate");
}

Extract from wikipedia: '...a regular expression (abbreviated regex or regexp) is a sequence of characters that forms a search pattern, mainly for use in pattern matching with strings'. So here: [A-Z][A-Z]([A-Z]|\\d)\\d\\d I have made an expression that consists of two capital letters, a capital letter or a number followed by two numbers.

Breaking the expression down further:

[A-Z] means any character in the range from A to Z (so capitals)

\\d means a digit.

| is the or operator in java

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top