简体   繁体   English

如何在不使用阵列的情况下检查车牌是否有效?

[英]How to check whether a license plate is valid or not without using arrays?

I was going to submit this code below but the TA said that I cannot use arrays.我打算在下面提交这段代码,但助教说我不能使用数组。 I'm not really sure how to do this without arrays.我不确定如何在没有数组的情况下做到这一点。 He said it was much simpler than what I did.他说这比我做的简单多了。

package b4;
import java.util.Scanner;
public class b2 {
    public static boolean isAlpha(String name) {
        char[] chars = name.toCharArray();
        for (char c : chars) {
           if (!Character.isLetter(c)) {
               return false;
           }
        }
        return true;
     }

     public static void main(String[] args)
     {
         Scanner scn=new Scanner(System.in);
         System.out.print("Enter a valid plate number: ");
         String plate=scn.next();

         if (plate.length()==5) {
             if (plate.contains("-")) {
                 String[] sp=plate.split("-");

                 if (isAlpha(sp[0])&&sp[0].length()==2) {
                     try {
                         Integer.parseInt(sp[1]);
                         System.out.println(plate+" is a a valid plate number.");
                     } catch(Exception e) {
                         System.out.println(plate+" is a an invalid plate number.");
                     }
                 } else {
                     System.out.println(plate+" is a an invalid plate number.");
                 }
             } else {
                 System.out.println(plate+" is a an invalid plate number.");
             }

         } else {
             System.out.println(plate+" is a an invalid plate number.");
         }
     }
}

Here was the question we were given originally which didn't mention we couldn't use arrays.这是我们最初给出的问题,它没有提到我们不能使用数组。

这里

Can you use RegEx?你可以使用正则表达式吗? If you can, it's pretty simple.如果可以的话,这很简单。

Your RegEx code could look something like this:您的 RegEx 代码可能如下所示:

\b[A-Z][A-Z]-[0-9][0-9]\b

You can then use the matches() function to check if the input works.然后您可以使用matches()函数来检查输入是否有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM