输出数组中的最小整数及其索引

时间:2016-12-05 20:15:04

标签: java

我一直在编写这个程序,但我有点卡住了,想要一些建议。这是我到目前为止所得到的:

import java.util.Scanner;

public class SmallestInArray
{
    public static void main(String[] args) 
    {
        int[] array = new int[10];
        input(array);
        output(array);
    }

    public static void input(int[] array)
    {
        Scanner kybd = new Scanner(System.in);
        System.out.println("Enter 10 integers: ");
        for (int i = 0; i < array.length; i++) {
            array[i] = kybd.nextInt();
        }
    }


    public static int findSmallest(int[] array, int first)
    {
        int smallestPos = first;
        for (int i = first + 1; i < array.length; i++) {
            if (array[i] < array[smallestPos]) {
                smallestPos = i;
            }
        }
        return smallestPos;
    }

    public static void output(int[] array)
    {
        for (int i = 0; i < array.length; i++) {
            System.out.print(array[i] + "  ");
        }
        System.out.println();
    }
}

除了findSmallest方法之外,一切都很好,因为我想输出最小的值和它的索引,但是我不太确定要传递什么作为参数主要方法?

2 个答案:

答案 0 :(得分:0)

试试这个

   public static void main(String[] args) 
    {
        int[] array = new int[10]; 
        input(array);
        output(array);

        int smallestPos = findSmallest(array, 0 /* P.S. this parameter seem to be useless */);
        int smallestVal = array[smallestPos];
        // output the two
    }

答案 1 :(得分:0)

请找到重构的代码,它可以获得数组中最小元素的值和索引。

    import java.util.Scanner;

public class SmallestInArray
{
    int index_of_smallest_element;
    public static void main(String[] args) 
    {
        int[] array = new int[10];
        input(array);
        SmallestInArray smallestInArray = new SmallestInArray();
        System.out.printf("Smallest Value:%d corresponding Index:%d\n",smallestInArray.findSmallest(array), smallestInArray.index_of_smallest_element);
        output(array);
    }

    public static void input(int[] array)
    {
        System.out.println("Enter 10 integers: ");
        try (Scanner kybd = new Scanner(System.in))
        {
            for (int i = 0; i < array.length; i++)
            {
                array[i] = kybd.nextInt();
            }
        }
    }

    public int findSmallest(int[] array)
    {
        int smallestValue = array[0];
        index_of_smallest_element = 0;
        for (int i = 1; i < array.length; i++) {
            if (smallestValue > array[i]) // it doesn't accounts for duplicate values
            {
                smallestValue = array[i];
                index_of_smallest_element = i;
            }
        }
        return smallestValue;
    }

    public static void output(int[] array)
    {
        for (int i = 0; i < array.length; i++) {
            System.out.print(array[i] + "  ");
        }
    }}

希望这有帮助