麻烦我的增强for循环? [英] Trouble with my enhanced for loop?
问题描述
编写一个名为contains()的方法,该方法接受一个整数和一个整数值的数组。如果数组包含指定的值,则该方法应该返回true,否则返回false。
$ $ $ $ $ $ $ $ $ $ $' ){
for(y:x){
}
}
我真的不明白他们是如何工作的,我显然需要返回一些东西? 如果
$ b
你要检查数组 y
中包含的数字 x
,你应该这样做:
boolean contains(int [] x,int y){
for(int i:x){
if (i == y)返回true;
}
return false;
$ / code>
这种类型的代表
循环通常被称为 for-each
。 int i:x
基本上意味着通过循环x并命名当前变量i
。那么如果当前变量 i
等于你正在寻找的变量(在你的情况下 - y
),那么返回true
。
so im having trouble understanding enhanced for loops..
Write a method called contains() that takes an array of integers and an integer value. The method should return true if the array contains the specified value, otherwise false.
boolean contains (int [] x, int y) {
for (y : x) {
}
}
i dont really get how they work i obviously need to return something?
If you want to check whether the number y
in contained within the array x
, you should do the following:
boolean contains (int [] x, int y) {
for (int i : x) {
if (i == y) return true;
}
return false;
}
This type of for
loop is often called for-each
. The int i : x
basically means Go through the loop 'x' and name the current variable 'i'
. Then if the current variable i
is equal to the one that you are looking for (in your case - y
) then return true
.
这篇关于麻烦我的增强for循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!