2016-12-05 71 views
-2

我一直在編寫這個程序,但我有一點卡住,想要一些建議。這是我到目前爲止有:輸出數組中的最小整數,它的索引

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法測得的其他,我想輸出的最小值和它的索引,但我不太清楚作爲主要方法中的參數傳遞?

+1

恰好是不工作怎麼辦?你期望輸出什麼?你會得到什麼輸出? – 2016-12-05 20:16:30

+0

那麼例如,如果我有System.out.println(findSmallest());我不知道要傳入什麼參數才能輸出最小值和索引 – Luke

+0

爲什麼添加'first'參數?去掉它。或者調用值爲'0'。 – Andreas

回答

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] + " "); 
     } 
    }} 

希望這有助於

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 
    }