2013-03-04 79 views
2

我只是试图查看输入的值是否与已经在数组中的值相匹配,以及它是否返回“有效”。我知道这是很简单的,但我不能得到这个工作:简单数组:检查值是否匹配

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); 
    } 
} 

谢谢你的任何援助(和耐心)

+2

7个问题和零接受?看到这[链接](http://meta.stackexchange.com/a/65088/155831) – Reimeus 2013-03-04 04:05:59

+1

http://stackoverflow.com/questions/1128723/in-java-how-can-i-test-if-an -array-contains-a-certain-value – 2013-03-04 04:11:45

+0

考虑将'accountNums'设置为'HashSet';检查“HashSet”中的值是否比循环“数组”更快。 – Akavall 2013-03-04 04:21:27

回答

6

使用equals方法。检查here为什么。

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

Jayamohan的答案是正确的,但我建议使用整数而不是字符串。这是一种更有效的方法,因为CPU处理数字(整数)比处理字符串要容易得多。

什么在这种情况下需要做的是改变newAccountaccountNumsint!而非String S和也是从accountNums初始化删除所有引号。您可以拨打keyboard.nextInt(),而不是致电keyboard.next(),它会返回一个整数。 if语句没问题。

1

你为什么使用数组?

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"; 

然后你只需要这个(没有循环):

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

此外,它更容易阅读和理解。

0

你不能比较== 字符串必须使用.equals()

相关问题