Я пытаюсь получить режим ввода десяти чисел в java

#java #oop #loops

#java #ооп #циклы

Вопрос:

 import java.util.*;
public class main {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] quiz = new int[10];
        int mean = 0,mode = 0,median,range;
        Scanner scan = new Scanner(System.in);
        for(int x=0;x<=9;x  ){
            System.out.print("Enter quiz[" (x 1) "]:");
            quiz[x]= scan.nextInt();
        }
        Arrays.sort(quiz);
        for(int x=0;x<=9;x  ){
            mean = mean quiz[x];
        }
        mean = mean/10;
        median = (quiz[4] quiz[5])/2;
        range = quiz[9]-quiz[0];
        int[] cntr = new int[10];
            for(int x=0;x<=9;x  ){
                for(int y=0;y<=9;y  ){
                    if (quiz[x]==quiz[y]amp;amp;x!=y){
                        cntr[x]  ;
                    }
                }
            }
        int[] sortcntr = cntr;
        int ndx = 0;
        Arrays.sort(sortcntr);
        for(int z=0;z<=9;z  ){
            if(cntr[z]==sortcntr[9]){
                ndx = z;
            }
            else 
                mode=0;
        }
        mode = quiz[ndx];
        System.out.println("Mean: " mean);
        System.out.println("Median: " median);
        System.out.println("Range: " range);
        if(mode==0){
        System.out.println("Mode: none");
        }
        else
            System.out.println("Mode: " mode);
        System.out.print(sortcntr[9]);
        System.out.print(cntr[9]);
        System.out.println(ndx);
    }

}
  

это коды, которые я использовал, все правильно, за исключением режима. переменная mode там всегда возвращает наибольшее число из числа. последняя часть была просто для отладки, а не для использования. пожалуйста, помогите

Комментарии:

1. Добро пожаловать в StackOverflow. Это помогло бы, если бы вы упомянули, что код предназначен для вычисления статистических показателей из нескольких выборок.

Ответ №1:

Основная проблема вашего кода заключается в том, что вы, очевидно, думаете, что строка

 int[] sortcntr = cntr;
  

создает копию массива cntr. Однако массивы имеют ссылочную семантику в Java. Таким образом, вы просто создаете вторую ссылку на тот же массив. Если вы затем отсортируете sortcntr, это также применимо к cntr, поскольку это тот же массив.

Для создания копии массива:

 int[] sortcntr = new int[ cntr.length ];
System.arraycopy(cntr, 0, sortcntr, 0, cntr.length);
  

Кстати: не имело бы больше смысла работать с числами с плавающей запятой (double) вместо целых чисел?

Комментарии:

1. я уже думал об этом, но не знаю никакого другого способа скопировать эти элементы этого массива, я не думал, что double необходим, потому что входные данные представляют собой просто целые числа. программа — это всего лишь упражнение, хотя

Ответ №2:

         for(int x=0;x<=9;x  ){
            for(int y=0;y<=9;y  ){
  

Внутренний цикл должен начинаться с x 1, иначе вы пересчитываете все дважды.

Ответ №3:

Просто чтобы помочь вам, если вы решите более обобщить (как сказал Раффаэле) процесс получения режима для данного набора данных, вот метод, который я разработал некоторое время назад, который даже вернет несколько режимов, если существует более одного с одинаковым вхождением. (Использует Java 8 Stream API)

 /**
 * Computes the mode of the passed integers.
 *
 * @param args Numbers to find the mode of.
 * @return Mode of the passed numbers.
 */
public static int[] mode(int... args) {
    /* Create a map of integers to their frequencies */
    Map<Integer, Integer> frequencies = IntStream.of(args).collect(
            HashMap::new,//Indicated that this collector will result in a HashMap
            (integerIntegerMap, value) -> integerIntegerMap.merge(value, 1, Maths::sum), //For each value in the arguments added, merge it with the current map and add the frequencies
            (integerIntegerMap, integerIntegerMap2) -> integerIntegerMap.putAll(integerIntegerMap2) //While this is not used, it simply combines 2 HashMaps. (I think this is only used when in parallel)
    );
    //Here we get the maximum number of occurrences for any number, we could return the mode here; but there could be multiple modes
    int maxOccurrences = frequencies.entrySet().stream().mapToInt(Map.Entry::getValue).max().getAsInt();
    //Here we simply go through the entry set again, filtering out only the numbers with a frequency equal to the max, then returning them as an array
    return frequencies.entrySet().stream().filter(entry -> entry.getValue() == maxOccurrences).mapToInt(Map.Entry::getKey).toArray();
}
  

-Томас

Ответ №4:

Поскольку входные данные уже отсортированы для вычисления диапазона и медианы, вы можете использовать следующий код, чтобы получить режим после одного цикла и без какой-либо дополнительной памяти (в режиме реального времени на ideone):

 // this must be sorted
int[] values = {1, 1, 2, 3, 4, 5, 5, 5, 6, 7, 8, 8};

int mode = values[0];
int modeOccurrences = 1;

int occurrences = 1;
int current = values[0];

for (int i = 1; i < values.length; i  ) {
    int value = values[i];
    if (value == current) {
        occurrences  ;
    } else {

        if (occurrences > modeOccurrences) {
            mode = current;
            modeOccurrences = occurrences;
        }

        occurrences = 1;
        current = value;
    }
}

if (occurrences > modeOccurrences) {
    mode = current;
    modeOccurrences = occurrences;
}
  

Вы даже можете обобщить этот фрагмент кода для работы с простыми объектами вместо числовых типов, при условии, что режимы можно сортировать и сравнивать (я использовал перечисления в своей демонстрации)