希望你们都过得愉快。我试图从一组大小为n的数字(从用户输入)返回第二大值的索引。我能够找到最大值以及第二大值,但似乎每当我尝试输出int类型的secondLargestIndex变量时,无论我做什么,它总是= 0表示输出。我已经使用变量largestIndex和secondLargestIndex更新了算法中的索引,并将它们放在整个程序的全局范围内(在main方法中),所以如果我没有弄错的话,变量会在全局范围内不断更新随着程序的运行。没有重复的任何变量让我更加确定,这就是为什么我很困惑。我跟踪它们并在适当时修改它们,同时跟踪值,但仍然输出0.如果你可以查看我的代码并提供一些反馈,我会非常感激。感谢您抽出宝贵时间帮助我。
import java.util.*;
public class hwk3_1 {
/* write an algorithm to find the 2nd largest element in a set containing n entries
*/
public static void main( String[] args) {
// declare needed variables
int[] arr;
int largest = 0, second_largest = 0, n = 0, largestIndex = 0,
secondLargestIndex = 0;
Scanner input = new Scanner(System.in);
// prompt user for size n
System.out.print("Please enter the size of your array: ");
n = input.nextInt();
arr = new int[n];
// take in input of size n from user
System.out.print("Please enter your set of int values: ");
for(int i = 0; i < n; i++){
arr[i] = input.nextInt();
}
// display to user their set of numbers
System.out.println("You entered: " + Arrays.toString(arr));
// output to the user what the 2nd largest number is
System.out.println("Second largest is: " + secondLargest(arr, largest,
second_largest, largestIndex, secondLargestIndex));
System.out.println("Second largest Index is: " +
findIndex_2ndLargest(arr, second_largest));
}// end main
// method secondLargest
public static int secondLargest(int[] arr, int largest, int second_largest,
int largestIndex, int secondLargestIndex) {
// traverse array to find 2nd largest num
for (int i = 0; i < arr.length; i++) {
// if the current index's value is greater than current largest,
then modify max & max2
if (largest < arr[i]) {
second_largest = largest;
secondLargestIndex = largestIndex;
largest = arr[i];
largestIndex = i;
// now we can traverse and see whether if there is a num larger than
2ndmax
} else if (second_largest < arr[i])
second_largest = arr[i];
secondLargestIndex = i;
}// end for loop
return second_largest;
}// end method secondLargest
// find the index of the second largest num
public static int findIndex_2ndLargest(int[] arr, int secondLargest){
int index = 0;
for(int i = 0; i < arr.length; i++){
if(arr[i] == secondLargest)
index = i;
}
return index;
}
}
我的输出 请输入您的阵列大小:5 请输入您的int值集:5 4 3 2 1 你输入了:[5,4,3,2,1] 第二大是:4 第二大指数是:0
渴望输出 请输入您的阵列大小:5 请输入您的int值集:5 4 3 2 1 你输入了:[5,4,3,2,1] 第二大是:4 第二大指数是:1