In my java program, I am trying to display a table of two single arrays in descending order. I have managed to display it in both ascending and descending order. However, there is an additional array element -1 in my terminal. The -1 can be seen in the picture attached below.
This is my attempt so far:
import java.util.*;
public class Q2_Frequency {
public static void main(String[] args) {
int sum = 0, mean, temp;
Scanner input = new Scanner(System.in);
System.out.println("Please enter the number of days: "); //take input from user
int n = input.nextInt();
int a[] = new int[n];
int b[] = new int[n];
int c = 0;
System.out.println("Please enter number of trucks using a road over the " + n + " day period: ");
for (int i = 0; i < n; i++) { //input into array
a[i] = input.nextInt();
sum = sum + a[i];
}
mean = sum / n;
System.out.println("The mean is: " + mean); // calculate mean of n day period
System.out.println("Sorted in ascending order");
System.out.println("Input\tFrequency");//print table in ascending order
for(int i = 0 ; i < n ; i++)
{
for(int j = i + 1 ; j < n ; j++)
{
if (a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
for (int i = 0; i < n; i++) {
c = 1;
if (a[i] != 1) {
for (int j = i + 1; j < n; j++) {
if (a[i] == a[j]) {
c = c + 1;
a[j] = -1;
}
}
b[i] = c;
}
}
for (int i = 0; i < n; i++) {
if (a[i] != -1)
{
System.out.println(a[i] + "\t\t\t"+ b[i]);
}
}
System.out.println("Sorted in descending order");
System.out.println("Input\tFrequency");//print table in ascending order
for(int i = 0 ; i < n ; i++)
{
for(int j = i + 1 ; j < n ; j++)
{
if (a[i] < a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
System.out.println(a[i] + "\t\t\t"+ b[i]);
}
ArrayLength(a);
}
private static void ArrayLength(int []array) // method to count number of inputs
{
if (array==null)
{
System.out.println("Number of input is 0.");
}
else
{
int arrayLength = array.length;
System.out.println("Number of input is: "+arrayLength);
}
}
}
Does anyone have an idea why the -1 appears only in the descending order and why?