java - How can I get my for each loop to print once for each number in the array -


assignment: write program reads in integers between 1 , 100 user , counts occurrences of each number. user input ends when enter 0. must use enhanced for-loop solve problem. if number occurs more 1 time use plural word “times” instead of “time”. not display numbers not entered.

i know , understand why code's current output below appears duplicates. print logic inside for-each loop code block. if close code block no longer able use variables initialized inside loop. have tried can think of. suggestions appreciated

current output:
- 1 occurs 1 time, - 1 occurs 2 times - 2 occurs 1 time - 2 occurs 2 times
- 3 occurs 1 time
- 3 occurs 2 times

needed output: - 1 occurs 2 times - 2 occurs 2 times - 3 occurs 2 times

package com.company; import java.util.scanner;  public class main {  public static void main(string[] args) {     scanner in = new scanner(system.in);     int[] numbers = new int[10];      system.out.print("enter integers:");     (int = 0; < numbers.length; i++) {         numbers[i] = in.nextint();         if (numbers[i] == 0) {             break;         }     }     enhancedloop(numbers);     }      private static void enhancedloop(int[] numbers) {         int[] counts = new int[101];          (int value : numbers) {             counts[value]++;              if (value > 0)                  if (counts[value]> 1)                      system.out.println(value + " occurs " + counts[value]+ " times");                  else                      system.out.println(value + " occurs " + counts[value] + " time");          } 

}

variables available in block in declared. move output after loop , iterate on counts display values:

for (int = 0, c = counts.length; < c; ++i) {     if (counts[i] > 0) {         if (counts[i] > 1) {             system.out.println(value + " occurs " + counts[i]+ " times");         } else {             system.out.println(value + " occurs " + counts[i]+ " time");         }     } } 

Comments

Popular posts from this blog

php - How to display all orders for a single product showing the most recent first? Woocommerce -

asp.net - How to correctly use QUERY_STRING in ISAPI rewrite? -

angularjs - How restrict admin panel using in backend laravel and admin panel on angular? -