[英]How to select the largest index of the smallest element in a single array Java
基本上,我需要找到數組中最小元素的最大索引。 第一個輸入是元素的數量。 但是,如果稍后在數組中重復相同的數字,則需要返回該索引。
現在我的代碼找到最小的數字並返回該數字的索引。 如何更新索引?
import java.util.Scanner;
public class smallestelement {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int length = input.nextInt();
int [] a = new int[length];
for (int i = 0; i < length; i++){
a[i] = input.nextInt();
}
// minimum
int min = a[0];
// counter
int index = 0;
// loop continues as long as i is less than the length of the array
for (int i = 0; i < a.length; i++){
min = a[i];
index = i;
}
System.out.println(index);
}
}
您需要使用if
語句來檢查您是否真的在查看較小的元素。 使用<=
進行比較,以便當您看到同樣最小值時,使用后面的索引。
for (int i = 1; i < a.length; i++) {
if (a[i] <= min) {
min = a[i];
index = i;
}
}
順便說一句,循環從 1 開始而不是 0 很好,因為您在循環之前使用索引 0 處的值初始化min
和index
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.