Chapter 7 Question 10 (Find the subscript of the smallest element)

Chapter 7 Question 10 (Find the subscript of the smallest element)

  • 7.10 (Find the subscript of the smallest element) Write a method to find the subscript of the smallest element in an integer array. If the number of such elements is greater than 1, the smallest subscript is returned. Use the following method header:
    public static int indexOfSmallElement(double[] array)
    Write a test program, prompt yoghurt to enter 10 numbers, call this method, return the subscript of the smallest element, and then display the subscript value.
    7.10 (Find the subscript of the smallest element) Write a method to find the index of the smallest element in the integer array. If the number of such elements is greater than 1, the smallest subscript is returned. Use the following method header:
    public static int indexOfSmallElement(double[] array)
    Write a test program, prompt yoghourt to enter 10 numbers, call this method, return the subscript of the smallest element, and then display the subscript value.
  • Reference Code:
package chapter07;

import java.util.Scanner;

public class Code_10 {
    
    
    public static void main(String[] args) {
    
    
        double[] array = new double[10];
        Scanner input = new Scanner(System.in);
        System.out.print("Enter 10 numbers: ");
        for (int i = 0;i < 10;i++)
            array[i] = input.nextDouble();
        System.out.println("The index of small element is " + indexOfSmallElement(array));
    }
    public static int indexOfSmallElement(double[] array){
    
    
        double min = array[0];
        int flag = 0;
        for (int i = 1;i < array.length;i++)
            if (min > array[i]) {
    
    
                min = array[i];
                flag = i;
            }
        return flag;
    }
}

  • The results show that:
Enter 10 numbers: 1.1 2.2 3.3 1.1 4.4 5.5 6.6 7.7 8.8 9.9
The index of small element is 0

Process finished with exit code 0

Guess you like

Origin blog.csdn.net/jxh1025_/article/details/109267572