2015-02-12 3 views
3

Я потерял, как сравнить 100 случайно сгенерированных чисел между 0-9 и значением массива, также между 0-9, а затем распечатать результаты. Будьте спокойны, я новичок в кодировании, и я знаю, что сосать. Мне кажется, что я на 75%. Я знаю, что есть способы сделать часть кода менее избыточной, однако я, похоже, борюсь с этими приемами.Подсчет событий с массивом - Java

Вот что я до сих пор:

public static void main(String[] args) { 
    double randomNum = 0; 
    for (int i = 0; i < 100; i++) { 
     randomNum = Math.random() * 10; 

    int count0 = 0, count1 = 0, count2 = 0, count3 = 0, count4 = 0; 
    int count5 = 0, count6 = 0, count7 = 0, count8 = 0, count9 = 0; 
    int [] arrayNums = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; 
    for (double j = 0; j <arrayNums.length; j++){ 
     if (arrayNums[0] == randomNum) { 
      count0++; 
     } 
     else if (arrayNums[1] == randomNum){ 
      count1++; 
     } 
     else if (arrayNums[2] == randomNum){ 
      count2++; 
     }else if (arrayNums[3] == randomNum){ 
      count3++; 
     }else if (arrayNums[4] == randomNum){ 
      count4++; 
     }else if (arrayNums[5] == randomNum){ 
      count5++; 
     }else if (arrayNums[6] == randomNum){ 
      count6++; 
     }else if (arrayNums[7] == randomNum){ 
      count7++; 
     }else if (arrayNums[8] == randomNum){ 
      count8++; 
     } 
     else{ 
      count9++; 
     } 

    } 
    System.out.print("Occurrences of 0: " + count0); 
    System.out.print("\nOccurrences of 1: " + count1); 
    System.out.print("\nOccurrences of 2: " + count2); 
    System.out.print("\nOccurrences of 3: " + count3); 
    System.out.print("\nOccurrences of 4: " + count4); 
    System.out.print("\nOccurrences of 5: " + count5); 
    System.out.print("\nOccurrences of 6: " + count6); 
    System.out.print("\nOccurrences of 7: " + count7); 
    System.out.print("\nOccurrences of 8: " + count8); 
    System.out.print("\nOccurrences of 9: " + count9); 
    } 
} 

}

Любые и вся помощь оценена.

+1

Oh look. Это дерево. Интересно, где лес? У вас уже есть один массив и один цикл, но тогда вы идете 'arrayNums [1]', 'arrayNums [2]' и т. Д. Вы можете использовать другой массив (счетчиков) и рудный цикл, чтобы сжать это примерно до 10 строк код. – John3136

+0

Вы можете использовать HashMap для этого. Это будет легко. Число -> Пара будет работать для вас. – TheLostMind

+0

@ TheLostMind вопрос говорит * «С массивом» * –

ответ

1

Ну, вместо того, чтобы использовать

int count0 = 0, count1 = 0, count2 = 0, count3 = 0, count4 = 0; 
int count5 = 0, count6 = 0, count7 = 0, count8 = 0, count9 = 0; 

Вы можете использовать:

int[] count = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; 

И ваш метод будет выглядеть так:

public static void main(String[] args) { 
     int[] count = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; 
     int[] arrayNums = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; 
     for (int i = 0; i < 100; i++) { 
      int randomNum = (int) (Math.random() * 10); 
      for (int j = 0; j < 10; j++) { 
       if (arrayNums[j] == randomNum) { 
        count[j]++; 
       } 
      } 
     } 
     for (int i = 0; i < 10; i++) { 
      System.out.println("Occurrences of " + i + ": " + count[i]); 
     } 
    } 
0

Вы называете случайное неправильным способом. это должно быть примерно так:

Random rnd = new Random(); 
int randomNum = rnd.nextInt(10); 

И вы вносите также переменную счетчика неправильно. Тогда ваш полный код будет выглядеть так:

public static void main(String[] args) { 
    Random random = new Random(); 
    int count0 = 0, count1 = 0, count2 = 0, count3 = 0, count4 = 0; 
    int count5 = 0, count6 = 0, count7 = 0, count8 = 0, count9 = 0; 
    for (int i = 0; i < 100; i++) { 
     int randomNum = random.nextInt(10); 


     int [] arrayNums = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; 
     for (double j = 0; j <arrayNums.length; j++){ 
      if (arrayNums[0] == randomNum) { 
      count0++; 
      } 
      else if (arrayNums[1] == randomNum){ 
      count1++; 
      } 
      else if (arrayNums[2] == randomNum){ 
      count2++; 
      }else if (arrayNums[3] == randomNum){ 
      count3++; 
      }else if (arrayNums[4] == randomNum){ 
      count4++; 
      }else if (arrayNums[5] == randomNum){ 
      count5++; 
      }else if (arrayNums[6] == randomNum){ 
      count6++; 
      }else if (arrayNums[7] == randomNum){ 
      count7++; 
      }else if (arrayNums[8] == randomNum){ 
      count8++; 
      } 
      else{ 
      count9++; 
      } 

     } 

    } 
    System.out.print("Occurrences of 0: " + count0); 
    System.out.print("\nOccurrences of 1: " + count1); 
    System.out.print("\nOccurrences of 2: " + count2); 
    System.out.print("\nOccurrences of 3: " + count3); 
    System.out.print("\nOccurrences of 4: " + count4); 
    System.out.print("\nOccurrences of 5: " + count5); 
    System.out.print("\nOccurrences of 6: " + count6); 
    System.out.print("\nOccurrences of 7: " + count7); 
    System.out.print("\nOccurrences of 8: " + count8); 
    System.out.print("\nOccurrences of 9: " + count9); 
} 
0

Вы возвращаете свои счетчики на 0 каждую итерацию цикла for. И я не знаю, для чего нужен второй цикл.

public static void main(String[] args) { 
    double randomNum = 0; 

    int count0 = 0, count1 = 0, count2 = 0, count3 = 0, count4 = 0; 
    int count5 = 0, count6 = 0, count7 = 0, count8 = 0, count9 = 0; 

    for (int i = 0; i < 100; i++) { 
     randomNum = Math.random() * 10; 

     switch(randomNum) { 
      case 0: count0++; break; 
      case 1: count1++; break; 
      case 2: count2++; break; 
      case 3: count3++; break; 
      case 4: count4++; break; 
      case 5: count5++; break; 
      case 6: count6++; break; 
      case 7: count7++; break; 
      case 8: count8++; break; 
      case 9: count9++; break; 
     } 

    } 


    System.out.print("Occurrences of 0: " + count0); 
    System.out.print("\nOccurrences of 1: " + count1); 
    System.out.print("\nOccurrences of 2: " + count2); 
    System.out.print("\nOccurrences of 3: " + count3); 
    System.out.print("\nOccurrences of 4: " + count4); 
    System.out.print("\nOccurrences of 5: " + count5); 
    System.out.print("\nOccurrences of 6: " + count6); 
    System.out.print("\nOccurrences of 7: " + count7); 
    System.out.print("\nOccurrences of 8: " + count8); 
    System.out.print("\nOccurrences of 9: " + count9); 
} 
1

Сначала добавьте все значения в array. Затем выполните итерацию массива и сохраните значение как ключ в HashMap, а значения - как количество вхождений. Затем после итерации у вас будет то, что вы пытаетесь архивировать здесь.

Например:

int[] arr = {0, 1, 0, 2, 5, 2, 4, 6, 0, 4, 7, 8, 9, 0, 2, 5, 7, 6}; 
Map<Integer, Integer> countMap = new HashMap<>(); 
    for (int i : arr) { 
    Integer currentCount = countMap.get(i); 
    if (currentCount != null) { 
     countMap.put(i, currentCount + 1); 
    } else { 
     countMap.put(i, 1); 
    } 
    } 
for(Map.Entry<Integer,Integer> entry:countMap.entrySet()){ 
     System.out.println("Number of occurrences of "+entry.getKey() 
                +" : "+entry.getValue()); 
} 
+0

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

+1

Не знаете, почему это было опущено. Исправление ... :) – alfasin

2
  • Использование HashMap, как счетчик является более элегантным, чем сохранять отдельную переменную для каждого элемента.
  • Используйте Random.nextInt(10) для генерации случайного числа от 0 до 9 (включительно).

    Map<Integer, Integer> counter = new HashMap<Integer, Integer>(); 
        Random rand = new Random(); 
        for (int i = 0; i < 100; i++) { 
         int randomNum = rand.nextInt(10); 
         Integer currentCount = counter.get(randomNum); 
         if (null == currentCount) { 
          counter.put(randomNum, 1); 
         } else { 
          counter.put(randomNum, currentCount+1); 
         } 
        } 
        for (Integer key : counter.keySet()) { 
         System.out.println(key + " -> " + counter.get(key)); 
        } 
    

Пример вывода

0 -> 12 
1 -> 10 
2 -> 9 
3 -> 6 
4 -> 8 
5 -> 9 
6 -> 11 
7 -> 12 
8 -> 14 
9 -> 9 
+0

вопрос говорит массивом –

+1

@ RandykaYudhistira OP также может спросить: «Как я могу пройти через плавательный канал?» и было бы глупо показывать ему, как вместо того, чтобы научить его, что он может использовать лодку ... Кроме того, даже если ему было запрещено использовать массив, его не очень сложно скопировать в хэшмап в качестве этапа инициализации: for (int i: arr) counter.put (i, 0); '- правильно? – alfasin

+0

Я бы по крайней мере рекомендовал «TreeMap», а не «HashMap», чтобы вы получили хороший упорядоченный вывод. –

Смежные вопросы