简体   繁体   中英

How do I create a counter for each element in an array?

So I have to write a program that reads an arbitrary number of integers that are in the range 0 to 50 inclusive and counts how many occurrences of each are entered. Indicate the end of the input by a value outside of the range. After all input has been processed., print all of the values (with the number of occurrences) that were entered one or more time.

public class problem
{
    public static void main(String[] args) 
    {
        Random rand = new Random(); 
        Scanner scan = new Scanner(System.in);

        int userInput = 0;
        ArrayList<Integer> myList = new ArrayList<Integer>();
        int index = -1;

        for (int num = 0; num <= userInput ; num++)
        {   
            System.out.println("Please enter a random number between 0 and 50, enter a negative number to end input: ");
            num--;

            if(userInput >= 0 || userInput <= 50)
            {       
                userInput++;
                userInput = scan.nextInt();
                index++;
                myList.add(userInput);
            }
            if (userInput < 0 || userInput > 50)
            {
                myList.remove(index);
                index--;
                break;
            }
        }   

        for (int num: myList)
            System.out.print(num + " ");

    }
}

This is what I have so far, but I am stuck as to how to count each integer occurrence in myList.

If I understand your question correctly, you can do something like this

        public static void main(String[] args) {
        int max = 200; // this is just for test
        HashMap<Integer, Integer> counter = new HashMap<>();
        for(int i = 0;i < max; i++){
            int value = (int) (Math.random() * 50); // generate random numbers
            if(counter.containsKey(value)){ // if map contains value, increment it's count
                counter.put(value, counter.get(value)+1);
            }else{
                counter.put(value, 1); //put it and start from 1
            }
        }
        System.out.println(counter);

    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM