This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center
                            
                        
                    
                
                7年前关闭。
            
        

我正在写一个方法检查数组包含多少个奇数。我的想法是,我使用for循环测试数字是否为奇数,如果为奇数,则将变量b加1,然后返回b作为奇数。我这样写:

for ( int a = 0, b = 0; values[a]%2==1;a++){
b++;
}

return b;


但是它给我一个错误“ return b;
       ^
b无法解决”。

我究竟做错了什么?

最佳答案

您不需要b值就不必检查数组的结尾。你有什么类似于

for (int a = 0; a < values.length;a++)
    if(values[a]%2!=1)
        return a;

// currently throws an exception.


您可能想要的是计算看起来像这样的奇数值的数量。

int count = 0;
for (int a = 0; a < values.length;a++)
    if(values[a] % 2 !=0)
        count++;
return count;


要么

int count = 0;
for (int v: values)
    count += v & 1;
return count;

关于java - 使用for循环测试数字是否为奇数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12349525/

10-13 07:17