user2101459
user2101459

Reputation: 599

Simple Array: Check to see if value matches

I am simply trying to see if the inputted value matches a value that is already in the array and if it does return "Valid". I realize this is very simple but I cannot get this to work:

 public static void main(String[] args) {

        Scanner keyboard = new Scanner(System.in);
        String[] accountNums = { "5658845", "8080152", "1005231", "4520125", "4562555",
                                 "6545231", "7895122", "5552012", "3852085", "8777541", 
                                 "5050552", "7576651", "8451277", "7881200", "1302850", 
                                 "1250255", "4581002" };

        String newAccount;
        String test = "Invalid";

        newAccount = keyboard.next();

        for (int i = 0; i < accountNums.length; i++)
        {        
            if(newAccount == accountNums[i])
            {
                test = "Valid";
            }
        }

        System.out.println(test);
    }
}

thank you for any assistance (and patience)

Upvotes: 2

Views: 6153

Answers (4)

Al-Zahir
Al-Zahir

Reputation: 1

You cannot compare strings with == You must use .equals()

Upvotes: 0

Bohemian
Bohemian

Reputation: 425043

Why are you using an array?

List<String> accountNums = Arrays.asList( "5658845", "8080152", "1005231", "4520125", "4562555",
     "6545231", "7895122", "5552012", "3852085", "8777541", 
     "5050552", "7576651", "8451277", "7881200", "1302850", 
     "1250255", "4581002" );

String test = "Invalid";

Then you just need this (no loop):

if (accountNums.contains(newAccount)) {
    test = "Valid";
}

Plus, it's easier to read and understand.

Upvotes: 1

ddmps
ddmps

Reputation: 4380

Jayamohan's answer is correct and working but I suggest working with integers rather than Strings. It is a more effective approach as CPUs handle numbers (integers) with a lot more ease than they handle Strings.

What has to be done in this case is change newAccount and accountNums to ints instead of Strings and also remove all the quotation marks from the accountNums initialization. Instead of calling keyboard.next() you can call keyboard.nextInt(), which returns an integer. The if-statement is fine as it is.

Upvotes: 3

Jayamohan
Jayamohan

Reputation: 12924

Use equals method. Check here why to.

if (newAccount.equals(accountNums[i]))

Upvotes: 6

Related Questions