I have to design a program that takes in arbitrary input from 0-50, prints out all the inputs ONCE, and then prints out the occurrence of each input.
I have it working to some degree, but, when the input is: 1 , 2 , 3 , 3 , 3 , 6 , 9 , 0 , 0
It prints out:
Input : Occurrence
Number Times
1 1
2 1
3 1
3 2
3 3
6 1
9 1
0 1
0 1
instead of:
Input : Occurrence
Number Times
0 2
1 1
2 1
3 3
6 1
9 1
This is a beginner course and most of the solutions I've seen online seem to be advanced using some kind of mapping technique that I haven't learned yet.
public static void main(String [] args)
{
int[] array = new int[51];
Scanner scan = new Scanner(System.in);
System.out.println("Number \t Times");
while (scan.hasNext()){
int x = scan.nextInt();
if (x>=0 && x<=50){
array[x]++;
System.out.println(x + "\t " + array[x]);
}
}
}
}
I've tried multiple ways of formatting the loops but I can't seem to find out how to get it to print a number that is input multiple times just once.
Here's another answer if you're still looking. I'll leave the hashmaps answer as other people might find that useful, but I decided to also get your current code working.
int[] numbers = new int[51];
// Small loop to get the number input
Scanner scanner = new Scanner(System.in);
for (int i=0; i<10; i++) {
System.out.print("> ");
int x = scanner.nextInt();
if (x >= 0 && x <= 50) {
numbers[x] += 1;
}
}
// Now display the results after getting input
System.out.println("Number \t Times");
for (int i=0; i<numbers.length; i++) {
if (numbers[i] != 0) {
System.out.println(i + "\t\t" + numbers[i]);
}
}