2012-01-24 31 views
9

Per il mio progetto, ho bisogno di creare un programma che contenga 10 numeri come input e mostri la modalità di questi numeri. Il programma dovrebbe utilizzare due array e un metodo che prende come parametro un array di numeri e restituisce il valore massimo nell'array.Come posso individuare e stampare l'indice di un valore massimo in un array?

Fondamentalmente, ciò che ho fatto fino ad ora viene utilizzato un secondo array per tenere traccia di quante volte appare un numero. Guardando l'array iniziale, vedrai che la modalità è 4. (Numero che appare di più). Nel secondo array, l'indice 4 avrà un valore di 2 e quindi 2 sarà il valore massimo nel secondo array. Devo trovare questo valore massimo nel mio secondo array e stampare l'indice. La mia uscita dovrebbe essere '4'.

Il mio programma va bene fino a quando non provo a produrre il '4', e ho provato alcune cose diverse ma non riesco a farlo funzionare correttamente.

Grazie per il vostro tempo!

public class arrayProject { 

public static void main(String[] args) { 
    int[] arraytwo = {0, 1, 2, 3, 4, 4, 6, 7, 8, 9}; 
    projecttwo(arraytwo); 
} 


public static void projecttwo(int[]array){ 
    /*Program that takes 10 numbers as input and displays the mode of these numbers. Program should use parallel 
    arrays and a method that takes array of numbers as parameter and returns max value in array*/ 
    int modetracker[] = new int[10]; 
    int max = 0; int number = 0; 
    for (int i = 0; i < array.length; i++){ 
     modetracker[array[i]] += 1;  //Add one to each index of modetracker where the element of array[i] appears. 
    } 

    int index = 0; 
    for (int i = 1; i < modetracker.length; i++){ 
     int newnumber = modetracker[i]; 
     if ((newnumber > modetracker[i-1]) == true){ 
      index = i; 
     } 
    } System.out.println(+index); 

} 
} 

risposta

8

L'errore è nel confronto if ((newnumber > modetracker[i-1]). Dovresti controllare se lo newnumber è più grande del massimo già trovato. Questo è if ((newnumber > modetracker[maxIndex])

si dovrebbe cambiare le tue ultime righe:

int maxIndex = 0; 
    for (int i = 1; i < modetracker.length; i++) { 
     int newnumber = modetracker[i]; 
     if ((newnumber > modetracker[maxIndex])) { 
      maxIndex = i; 
     } 
    } 
    System.out.println(maxIndex); 
+0

Per un lavoro etichettato domanda è più opportuno per puntare a ciò che è sbagliato con il lavoro di Op invece di fornire una soluzione letterale –

+0

Sì, lo ha modificato. – isah

+0

ok, grazie- seguo il codice e lo capisco. Grazie! – pearbear

1

Si potrebbe cambiare ultima parte di:

int maxIndex = 0; 
for (int i = 0; i < modetracker.length; i++) { 
    if (modetracker[i] > max) { 
     max = modetracker[i]; 
     maxIndex = i; 
    } 
} 
System.out.println(maxIndex); 
Problemi correlati