Thorchaq
Thorchaq

Reputation: 1

Java code always returns error message (valid never equals true)

My boolean valid variable always seems to return false, which triggers the else error message. Any ideas why? I am trying to convert from bar code to zip code, and I have to check for data validation (make sure that only : and | are used for the barcode, and make sure that it is only 32 characters long. Then, I have to ignore the first and last | and only count the first 5 bar codes (lines 1-25 in the actual string/barcode.)) Then I convert whatever barcode I have in 1-25 into a zipcode/digits.

public class JordanReynoldsHW7 
{
    public static void main(String[] args) 
    {
        String barCode = "|||:::||:::||:::||:::||:::||:::|";
        boolean valid;
        valid = true;
        if (barCode.length() != 32)
            valid = false;
        for (int i = 0; i < barCode.length(); i++)
            if (barCode.charAt(i) != ':' || barCode.charAt(i) != '|')
                valid = false;

        if (valid == true) {
            String zipCode = "";
            for (int i = 1; i <= 25; i = i + 5)
                zipCode += getNumber(barCode.substring(i, i + 5));
            System.out.println(zipCode);
        } else
            System.out.print("error message");
    }

    public static int getNumber(String s) 
    {
        switch (s) {
            case "||:::":
                return 0;
            case ":::||":
                return 2;
            case "::|:|":
                return 3;
            case ":|::|":
                return 4;
            case ":|:|:":
                return 5;
            case ":||::":
                return 6;
            case "|:::|":
                return 7;
            case "|::|:":
                return 8;
            default:
                return 9;
        }
    }
}

Upvotes: 0

Views: 408

Answers (3)

LarrySellers
LarrySellers

Reputation: 60

The line

if(barCode.charAt(i) !=':' || barCode.charAt(i) != '|')

should read:

if(barCode.charAt(i) !=':' && barCode.charAt(i) != '|')

As the only options are for it to contain one or the other the first statement will always return true;

Upvotes: -1

rgettman
rgettman

Reputation: 178263

Your logic in this line is incorrect:

if(barCode.charAt(i) !=':' || barCode.charAt(i) != '|')

The character is always not ':' or not '|', so valid is always getting set to false. You want "and", with &&. Try

if(barCode.charAt(i) !=':' && barCode.charAt(i) != '|')

Upvotes: 4

Eran
Eran

Reputation: 393841

Change

 if(barCode.charAt(i) !=':' || barCode.charAt(i) != '|')
     valid=false;

to

 if(barCode.charAt(i) !=':' && barCode.charAt(i) != '|')
     valid=false;

The current condition you have would always return true (since every character is either not ':' or not '|'), and therefore valid would always be false.

Upvotes: 3

Related Questions