This discussion is archived
1 Reply Latest reply: Nov 27, 2012 5:13 AM by aksarben RSS

Working with arrays need help

976409 Newbie
Currently Being Moderated
Write a program that reads numbers from the keyboard into an array of type?
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 disticnt 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

this is what i done but i don't know how to sort them from largest to smallest. i don't know how to tell the program that it can't be more than 50 numbers. any time i test the program i can't type any negative numbers. please help! im new to java and i try my best thanks in advance

import java.util.Scanner;

public class SortNumbers50 {

public final int ARRAY_SIZE = 50;

public static void main(String[] args) {

Scanner keyboard = new Scanner(System.in);

System.out.println("How many numbers do you want to enter? Up to 50");
int size = keyboard.nextInt();
int[] n = new int[size];


getValues(n);

System.out.println("N Count");

showArray(n);
}

private static void getValues(int[] array) {
Scanner keyboard = new Scanner(System.in);
int check;
System.out.println("Enter " + array.length + " numbers");

for (int adding = 0; adding < array.length; adding++) {
System.out.print("Enter number " + (adding + 1) + ": ");
check = keyboard.nextInt();
if (check >= -10000 && check < 10000) {
array[check]++; //increment count at position
} else {
break;

}}
}

public static void showArray(int[] array) {
for (int count = 0; count < array.length; count++) {
if (array[count] != 0) //print what has been entered by user
{
System.out.println(count + " " + array[count] );
}
}
}
}

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points