2

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)

user2101459
  • 579
  • 2
  • 8
  • 19
  • 1
    http://stackoverflow.com/questions/1128723/in-java-how-can-i-test-if-an-array-contains-a-certain-value – βhargavḯ Mar 04 '13 at 04:11
  • Consider making `accountNums` a `HashSet`; it is faster to check if a value is in a `HashSet` than to loop over an `array`. – Akavall Mar 04 '13 at 04:21

4 Answers4

6

Use equals method. Check here why to.

if (newAccount.equals(accountNums[i]))
Community
  • 1
  • 1
Jayamohan
  • 12,734
  • 2
  • 27
  • 41
3

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.

ddmps
  • 4,350
  • 1
  • 19
  • 34
1

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.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
0

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