Issue
I'm doing this as a practice problem for arrays and I am having a hard time figuring out how to get it to actually count the input.
The full problem reads:
"Design and implement an application 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. After all input has been processed, print all of the values (with the number of occurrences) that were entered one ore more times."
Perhaps the chapter didn't explain much or I am just not grasping the concept but I can't think of any way to really get started on this. I've looked around on Google and some of the solutions that were posted still don't make sense (some don't even work when I tested to see what they did!) and was hoping I could get some pointers on what to do here.
My code so far:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int[] array = new int[51];
Scanner input = new Scanner(System.in);
System.out.println("Please enter a number");
while (input.hasNext()){
int x = input.nextInt();
if (x>=0 && x<=50) //
array[x]++; //should make array size equal to x + 1?
}
}
hopefully I'm on the right track here.
Solution
Apart from jedwards reply, I suppose you need the individual occurance of all accepted input. If that is the case try this
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class OccuranceCounter {
public static void main(String[] args) {
Map<Integer, Integer> counter = new HashMap<Integer, Integer>();
Scanner input = new Scanner(System.in);
System.out.println("Please enter a number or -1 to quit");
while (input.hasNext()) {
int x = input.nextInt();
if (x >= 0 && x <= 50){
Integer val = counter.get(x);
if(val == null){
counter.put(x, 1);
} else {
counter.put(x, ++val);
}
} else if(x == -1){
break;
}
}
for(Integer key : counter.keySet()){
System.out.println(key + " occured " + counter.get(key) + " times");
}
}
}
Answered By - Syam S
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.