SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Walter Savitch ,kenrick Mock
Chapter:
Arrays
Exercise:
Programming Projects
Question:6 | ISBN:9780132830317 | Edition: 5

Question

Write a program that reads numbers from the keyboard into an array of type int[]. You may assume that there will be 50 or fewer entries in the array. Your program allows any number of numbers to be entered, up to 50. The output is to be a two-column list. The first column is a list of the distinct array elements; the second column is the count of the number of occurrences of each element. The list should be sorted on entries in the first column, largest to smallest.

For the array

–12 3 –12 4 1 1 –12 1 –1 1 2 3 4 2 3 –12

the output should be

N Count

4 2

3 3

2 2

1 4

–1 1

–12 4



TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer


package numberarray;

import java.util.*;

public class NumberArray {
    
    private static void reverseSort(int arr[]) {
        for(int i =0; i < arr.length; i++) {
            arr[i] = (arr[i] * -1);
        }
        Arrays.sort(arr);
        for(int i =0; i < arr.length; i++) {
            arr[i] = (arr[i] * -1);
        }
}
       
    private static void getCountTable(int arr[]) {
        int count = 1;
        System.out.printf("Number Count\n");
        for (int i = 0, length = arr.length; i < length; i++) {
        if (i < length - 1) {
            if (arr[i] == arr[i + 1]) {
                count++;
            }
        } else {
            
            System.out.printf("%6d%6d\n", arr[i], count);
        }
        if (i < length - 1 && arr[i] != arr[i + 1]) {
            
            System.out.printf("%6d%6d\n", arr[i], count);
            count = 1;
        }
    }
}
       
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        
        System.out.println("How many number entries in the array? (at most 50)");
        int[] numberArray = new int[input.nextInt()];
        
        System.out.println("Enter in the array numbers with a space: ");
        for(int i = 0; i < numberArray.length; i++) {
            numberArray[i] = input.nextInt();
        }
       
        reverseSort(numberArray);
        getCountTable(numberArray);
    
    }
}
    

 

1 0

Discussions

Post the discussion to improve the above solution.