gpt4 book ai didi

java - 返回给定位置的数组元素的方法?

转载 作者:行者123 更新时间:2023-12-02 06:13:02 25 4
gpt4 key购买 nike

我正在尝试编写一个方法,该方法采用 int 参数,如果传递的 int 参数小于数组长度,则返回给定数组的元素。如果有人能指出我正确的方向,我将不胜感激。

代码:

String[] fruits = {"jan","feb","mar","apr","may","jun","jul","aug","sept","oct"};



public String getStr( int pos ){

String str;

if( pos <= fruits.length){

for( int i=0; i < fruits.length; ++i){
if(fruits[i] == pos){

str = fruits[pos];

}//IF
}
}//IF
else{
str = null;
}
return str;
}//METOD

最佳答案

  1. 数组数据结构提供基于数组索引的随机访问。因此,您不需要遍历数组,直到到达所需的位置。您可以直接访问它。
  2. 在 Java 中(与大多数编程语言一样),数组是从 0 索引的。这意味着对于大小为 n 的数组,数组的索引将从 0 变化到 n-1。因此,任何索引<0或index>=n都会导致ArrayIndexOutofBounds异常。

记住这些事情,以下代码将按预期工作:(假设“pos”表示基于 0 索引计数的数字)

String[] fruits = {"jan","feb","mar","apr","may","jun","jul","aug","sept","oct"};
public String getStr(int pos) {
if( pos < fruits.length && pos > -1){
return fruits[pos];
}
return null;
}

关于java - 返回给定位置的数组元素的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21720243/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com