如何检查元素是否在java中的数组中?

Bob*_*Bob 1 java arrays

如何检查元素是否在java中的数组中?

        int[] a = new int[5];
        a[0] = 5;
        a[1] = 2;
        a[2] = 4;
        a[3] = 12;
        a[4] = 6;
        int k = 2;
        if (k in a) { // whats's wrong here?
            System.out.println("Yes");
        }
        else {
            System.out.println("No");
        }
Run Code Online (Sandbox Code Playgroud)

谢谢!

McS*_*tch 6

java中的"foreach"语法是:

for (int k : a) { // the ':' is your 'in'
  if(k == 2){ // you'll have to check for the value explicitly
    System.out.println("Yes");
  }
}
Run Code Online (Sandbox Code Playgroud)