Lyra Orwell
Lyra Orwell

Reputation: 1258

Incorrect Logic in Java

I am trying to write a logic statement which states "IF newID does not have 6 characters OR newID does not start with EITHER M,P,T,O then error.

This is the statement I have so far using java:

if ((newID.length() != 6) || !(newID.charAt(0)!='M'&& newID.charAt(0)!='P'&& newID.charAt(0)!='T'&& newID.charAt(0)!='O'))

A valid newID code would be:

M44521
PU2212

An invalid code would be:

6
P32
R55553

Upvotes: 0

Views: 67

Answers (4)

nice_dev
nice_dev

Reputation: 17805

In your condition, you use &&(and) along with ! which needs to be removed as pointed by @Pankaj in his answer. So it would look like:

if (newID.length() != 6 || newID.charAt(0)!='M' && newID.charAt(0)!='P' && newID.charAt(0)!='T' && newID.charAt(0)!='O')

As an alternative, you can also use || (or) condition. So, your final condition would be:

if (newID.length() != 6 || 
    !(newID.charAt(0) == 'M' ||
      newID.charAt(0) =='P' || 
      newID.charAt(0) == 'T' ||
      newID.charAt(0) =='O')
    ){
    // throw your exception
}

You can make this more neat with

if (newID.length() != 6 || "MPTO".indexOf(newID.charAt(0)) == -1){
    // throw your exception
}

Upvotes: 1

Pankaj Dadwal
Pankaj Dadwal

Reputation: 21

The Correct output is not coming due to the !. In your code,

if ((newID.length() != 6) || !(newID.charAt(0)!='M'&& newID.charAt(0)!='P'&& newID.charAt(0)!='T'&& newID.charAt(0)!='O'))

There is ! after || which is making whole logic incorrect.

Upvotes: 0

Faraz
Faraz

Reputation: 6265

I have written a test program which you can use to test continuously by plugging in values:

public class TestProgram {

    public static void main(String[] args) {
        String newID = "";
        test(newID);
        newID = "M44521";
        test(newID);
        newID = "PU2212";
        test(newID);
        newID = "6";
        test(newID);
        newID = "P32";
        test(newID);
        newID = "R55553";
        test(newID);
        newID="P12345";
        test(newID);
    }

    private static void test(String newID) {
        int leng = newID.length();
        if (leng > 0) {
            char c = newID.charAt(0);
            if (c != 'M' && c != 'P' && c != 'T' && c != 'O' || leng != 6) {
                System.out.println("Problem!");
            }
            else {
                System.out.println("No Problem");
            }
        }
    }

}

Output so far:

No Problem

No Problem

Problem!

Problem!

Problem!

No Problem

Upvotes: 1

Try

if ((newID.length() == 6) && !( newID.charAt(0)=='M' || newID.charAt(0)=='P' || newID.charAt(0)=='T' ||  newID.charAt(0)=='O')){

// do stuff with valid newID
}

Upvotes: 0

Related Questions