[英]How can I set arrays in Java?
Here is my code: 这是我的代码:
int setElement(int[]array) {
int key;
for (int i=0; i<array.length; i++) {
}
return key;
}
Something is wrong here. 这里不对劲。
As you said, your method needs to take three
parameters, but your method takes just one input array
. 如您所说,您的方法需要使用three
参数,但是您的方法仅需要一个输入array
。 Also there is no need to loop
through the array
, array
element can be accessed using its index
for insertion
, also for retrieval
. 也没有必要以loop
通过所述array
, array
元素,可以使用其来访问index
为insertion
,也可用于retrieval
。 Since the index
is passed as parameter
you can use it directly in your code. 由于index
是作为parameter
传递的,因此您可以直接在代码中使用它。
All you need to do is 您需要做的就是
public void setValueInArray(int[] array, int index, int value){
if(array != null && index >= 0 && index < array.length){
array[index] = value;
}
}
Try to pass the index and the value you are trying to change. 尝试传递索引和您要更改的值。
public void setElement(int[] array, int index, int val ) {
if(array!=null && index >-1 && index<array.length ){
array[index]=val ;
} else{
//sorry not possible
}
}
key
should be passed to the method. key
应传递给方法。
The way you're doing it you'll never meet the if
condition since key
has a garbage value - It's only declared but never defined. 您执行此操作的方式永远不会满足if
条件,因为key
具有垃圾值-仅声明但从未定义。
Integer myArray[]= {12,23,10,22,10};
System.out.println(Arrays.asList(myArray).indexOf(23));
use above code 使用上面的代码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.