I'm implementing algorithm which will count the appearance of unique numbers in linked list. The problem is in the for loop in which I'm counting the appearance, when the input is something like 1 1 1 2 2 2
Instead of getting for output
1 appearance 3 times
2 appearance 3 times
I'm getting
1 appearance 3
0 appearance 0
Wiht the input 1 2 3 4 5 6 7 8 9 I got array out of index exception. Here's the code
public static void main(String[] args) {
LinkedList<Integer> list = new LinkedList<Integer>();
Scanner user_input = new Scanner(System.in);
String input = user_input.nextLine();
//Getting user input, if the user enter an empty line(enter, enter) the loop will die
while(input.length() > 0){
list.add(Integer.parseInt(input));
input = user_input.nextLine();
}
Collections.sort(list); //sorting the input
//Getting the number of unique numbers
int count_of_unique_numbers = 1;// There will be atleast one unique number
if(!list.isEmpty()){
int temp = list.get(0);
for(int i = 1;i < list.size(); i++){
if(temp != list.get(i)){
count_of_unique_numbers++;
temp = list.get(i);
}
}
}
else{
System.out.println("The list is empty");
return;
}
//Counting how many times the unique numbers apper;
int number_appearance[][] = new int[count_of_unique_numbers][2];
int temp = list.get(0);
int counter = 1;
int j = 0;
for(int i = 1;i < list.size();i++){
if(temp == list.get(i)){ counter++; }
else{
number_appearance[j][0] = temp;
number_appearance[j][1] = counter;
counter = 1;
temp = list.get(i);
j++;
}
}
//Printing the number_appearance array
for(int i = 0; i < count_of_unique_numbers; i++){
System.out.println("The number: " + number_appearance[i][0] + " appearece " + number_appearance[i][1] + " times");
}
}