Program reads numbers from keyboard into an array


Discussion:

Q: Write a program that reads numbers from the keyboard into an array of type int[]. Assume that there will be 50 or fewer entries in the array. The program should allow any number of numbers to be entered, up to 50 numbers. 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 the occurrences of each element. Sort the list on entries in the first column, largest to smallest. For example:

If the following elements are input into the array -12 3 -12 4 1 1 -12 1 -1 1 2 3 4 2 3 -12

the output would be:

Num Count
4 2
3 3
2 2
1 4
-1 1
-12 4

import java.util.Scanner;

public class ArrayElements
{
public static void main( String args[ ] )
{
//Scanner keyboard = new Scanner( System.in );

//System.out.println( "Enter up to 50 elements" )

final int ARRAY_LENGTH = 49; // declare constant
int array [ ] = new int[ ARRAY_LENGTH ]; // create array

// calculate value for each array element
for ( int counter = 0; counter < array.length; counter++ )

array[ counter ] = 2 + 2 * counter;

System.out.printf( "%s%8s\n", "InputNumber", "NumberOfOccurrences" ); // column headings, sort 1st col entries Lrg to Small

// output each array element?s value
for ( int counter = 0; counter < array.length; counter++ )
System.out.printf( "%5d%8d\n", counter, array[ counter ] );
} // end main
} // end class Init Array

Solution Preview :

Prepared by a verified Expert
Data Structure & Algorithms: Program reads numbers from keyboard into an array
Reference No:- TGS01931870

Now Priced at $20 (50% Discount)

Recommended (98%)

Rated (4.3/5)