gpt4 book ai didi

java - 返回索引 vector

转载 作者:行者123 更新时间:2023-12-02 03:38:54 27 4
gpt4 key购买 nike

1-嘿,我是编程新手,但如果你们能帮助我,我会很感激,我需要在这个方法中返回将从主方法接收的 vector 的最大值,但我还需要返回主方法方法捕获了最大值的索引,那么我该怎么做呢?

  public static int maxOfaVector (int[] vector){
int max = vector[0];
int school;
for(int i=0; i<vector.length; i++){
if(vetor[i] > vector[0]){
max = vector[i];
}
}
return max;
}

最佳答案

不,一种方法只能返回一个值。幸运的是,这就是这里所需要的,因为您所需要做的就是让该方法返回最大值的索引,就像它已经编写的那样。一旦有了这个,调用代码就可以轻松地从数组中获取最大值。

// in the main method
// assuming an int array called myArray
int maxIndex = maxOfaVector(myArray);
int maxValue = myArray[maxIndex];

问题:

  • 您的代码有一个拼写错误,if(vetor[i]应该是if (vector[i]
  • 还有一个逻辑错误。在相同的 if boolean 测试中,您应该测试 if (vector[i] > vector[max])不是if (vector[i] > vector[0])
  • 此外,您应该首先进行测试以确保数组的长度 > 0。

关于java - 返回索引 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37081613/

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