Java if 语句错误

Java if 语句错误

这是我的代码:

    while(valid==false)
    {
        System.out.println("Please enter a reference number which is two letters followed by three digits and a letter(B for business accounts and N for non business accounts)");
        ref = keyboard.nextLine();       

        if (ref.length() != 6)
        {
            System.out.println("The reference number must be 6 characters long");
            errors = errors + 1;
        }            

        if ((Character.isDigit(ref.charAt(0))== true) || (Character.isDigit(ref.charAt(1))== true))
        {
            System.out.println("The first 2 characters must be letters");
            errors = errors + 1;
        }

        if ((Character.isDigit(ref.charAt(2))== false) || (Character.isDigit(ref.charAt(3))== false)||(Character.isDigit(ref.charAt(4))== false))
        {
            System.out.println("The 3rd,4th and 5th characters must be numbers");
            errors = errors + 1;
        }

        if ((!ref.toUpperCase().endsWith("B"))||(!ref.toUpperCase().endsWith("N"))) 
        {
            System.out.println("The 6th character must be either B(for business accounts) or N(for non business accounts) ");
            errors = errors + 1;
        }

        if (errors==0)
        {
            valid=true;
        }
    }

    return ref;

当使用引用 aa123b(接受状态)运行程序时,它会显示:“第 6 个字符必须是 B(对于商业帐户)或 N(对于非商业帐户)”

它不应该显示任何内容而应该返回字符串。

答案1

如果最后一个字符必须是BN,则代码中的条件是错误的。而不是

(!ref.toUpperCase().endsWith("B")) || (!ref.toUpperCase().endsWith("N"))

它应该是

(!ref.toUpperCase().endsWith("B")) && (!ref.toUpperCase().endsWith("N"))

你需要and而不是or。请这样理解:“如果最后一个字母不是 B最后一个字母不是 N,则错误”

相关内容