2016-10-26 70 views
0

該程序需要十個用戶輸入整數,並將它們存儲到一個數組中。它應該找到最大的值,並找到值的索引。目前,它發現最大的價值。隱藏數組值索引

但是,我不知道如何使它找到該值的索引。我覺得我可能會過分複雜化一個簡單的解決方案。任何幫助或建議,將不勝感激,謝謝!

public static void main(String[] args) { 

    int[] numbers; 
    numbers = new int[10]; 
    int largest = numbers[0]; 
    int counter; 

    Scanner keyboard = new Scanner(System.in); 

    System.out.println("Please enter 10 numbers: "); 

    for (counter = 0; counter < numbers.length; counter++) { 
     numbers[counter] = keyboard.nextInt(); 
    } 


    for (int i : numbers) { 

     if (i > largest) { 
      largest = i; 

     } 
    } 
    System.out.print("The largest number is: " + largest); 
    System.out.println(" "); 
    System.out.print("That number is stored at index " + ); 
    } 
} 

回答

2

田徑最大的,它的位置同時

public static void main(String[] args) { 

    int[] numbers; 
    numbers = new int[10]; 
    int largest = numbers[0]; 
    int largest_i = 0; 
    int counter; 

    Scanner keyboard = new Scanner(System.in); 

    System.out.println("Please enter 10 numbers: "); 

    for (counter = 0; counter < numbers.length; counter++) { 
     numbers[counter] = keyboard.nextInt(); 
     if (numbers[counter] >= largest) { 
      largest = numbers[counter]; 
      largest_i = counter; 
     } 
    } 

    System.out.print("The largest number is: " + largest); 
    System.out.println(" "); 
    System.out.print("That number is stored at index " + ); 
    } 
} 
0

你或許可以創建一個名爲「largestIndex」來存儲索引值的變量。

而不是使用foreach循環,使用for循環從0到numbers.length進行迭代,每當您找到一個大於'最大'的數字時,就更新largestIndex變量。