简体   繁体   English

在Java中的增强型for循环中使用xor运算符

[英]Using xor operator in enhanced for loop in Java

sorry if this is a duplicate but I tried my hardest and couldn't find what exactly I'm doing wrong. 很抱歉,如果这是重复的操作,但我尽了最大努力,却找不到我做错了什么。 I'm working on java concepts in hopes to take the certification exam in the upcoming year, and I'm playing around with enhanced for loops and getting used to using them. 我正在研究Java概念,希望在来年参加认证考试,而且我正在尝试使用增强的for循环并习惯于使用它们。 I tried making an enhanced for loop to search through an array, and using the xor (^) operator I'm wanting to determine the location of an element that matches another variable. 我试图制作一个增强的for循环来搜索数组,并使用xor(^)运算符来确定与另一个变量匹配的元素的位置。 the code I currently have is: 我目前拥有的代码是:

int[] x = {17, 16, 15};
    int y = 16;
    int z;
    for (int a : x) {
        z = x[a]^16;

        if (z==0)
            System.out.println(a);
        else;
    }

I can't seem to figure out why I'm getting an error. 我似乎无法弄清楚为什么会出错。 I know it has to do with the way I'm accessing the array at (z=x[a]^16), is there a better way to write this that I'm just not seeing? 我知道这与我访问(z = x [a] ^ 16)处的数组的方式有关,有没有更好的方式编写我没看到的代码? Thanks for the help in advanced. 感谢您的帮助。

The enhanced for loop provides each element in the array or list, not the index to the element. 增强的for循环提供数组或列表中的每个元素,而不是元素的索引。 So, the first time around, a = 17. x[17] should give an array index exception. 因此,第一次出现a =17。x [17]应该给出数组索引异常。 Note that your code compiles only because you created an array of int; 请注意,代码的编译仅是因为您创建了一个int数组。 if it was an array of String, then you would end up with a compile error. 如果它是String的数组,那么最终将导致编译错误。

In the future, include the error messages you get when you run your code. 将来,请包含您在运行代码时收到的错误消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM