有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java注册模式中的无效数据段

我需要使用一个六个字母的单词,如果它有一个字母数字序列,那么它将是一个有效的数据段。否则将被视为无效。我的代码的问题是,它总是以有效的方式运行。这是我的代码:

        vstatus=false;

        char a=pcode.charAt(0);
        char b=pcode.charAt(1);
        char c=pcode.charAt(2);
        char d=pcode.charAt(3);
        char e=pcode.charAt(4);
        char f=pcode.charAt(5);

        if(!Character.isLetter(a)) vstatus=true;
        if(!Character.isDigit(b)) vstatus=true;
        if(!Character.isLetter(c)) vstatus=true;
        if(!Character.isDigit(d)) vstatus=true;
        if(!Character.isLetter(e)) vstatus=true;
        if(!Character.isDigit(f)) vstatus=true;

        if (vstatus=true)
        {
            System.out.println(convertUpperCase(pcode)+" is a valid postal code");
        }
        if (vstatus=false) 
        {
            System.out.println(convertUpperCase(pcode)+" is not a valid postal code");
        }

共 (1) 个答案

  1. # 1 楼答案

    我想这将是针对您的问题的较短代码:

        String pcode = "aza2a3";
        String regex = "[A-Za-z]{1}[\\d]{1}[A-Za-z]{1}[\\d]{1}[A-Za-z]{1}[\\d]{1}";
        boolean matches = pcode.matches(regex);
        System.out.println(matches);
    

    如果字符串的格式符合要求,则matches为true;如果我与所需字符串不匹配,则matches为false