Frequency Array and Histogram in Java - java

I have to make the following program.
Write a program that builds a frequency array for data values in the range 1 to 20 and then prints their histogram. The data is to be read as input from the user. Add the following functions to your program:
a. The getData function takes input from the user and stores the data in an array.
b. The printData function prints the data in the array.
c. The makeFrequency function examines the data in the array, one element at a time, and adds 1 to the corresponding element in a frequency array based on the data value.
d. The makeHistogram function prints out a vertical histogram using asterisks for each occurrence of an element. For example, if there were five value 1s and eight value 2s in the data, it would print
1: *****
2: ********
I managed to make getData function but I can't make the other 3. Any help would be appreciated. Here is my code
import java.util.Scanner;
public class FrequencyArray {
static Scanner scan = new Scanner(System.in);
public void getData() {
System.out.println("Enter the size of array: ");
int nums = scan.nextInt();
int[] a = new int[nums];
for (int i = 1; i < a.length; i++) {
System.out.print("Enter the numbers: " + i + ":");
a[i] = scan.nextInt();
}
}
public void printData() {
getData();
}
public static void main(String[] args) {
FrequencyArray array = new FrequencyArray();
array.getData();
}
}

To print such an array, all you would need is another for-loop - loop from 0 to the array's length, and print both the loop counter's value, and the value stored in the array at that index.
System.out.println(index + ":" + array[index]);
For the histogram, do a similar loop, but for each value of the array, append an asterisk to the current line for however many instances of said number there are.
System.out.print(index);
//from 0 to the amount of this number, call System.out.print("*");
System.out.println();

Use TreeMap to store the number and their frequency in a sorted order once you get the data
then iterate over the TreeMap to print the number followed by the stars denoting the count of the value
public void printData() {
int [] numArray = getData();
Map<Integer,Integer> valueCountMap = new TreeMap();
for(int i=0;i<numArray.length;i++) {
int num = numArray[i];
if(valueCountMap.get(num) == null) {
valueCountMap.put(num,0);
}
int count = valueCountMap.get(num);
valueCountMap.put(num,count+1);
}
for(Map.Entry<Integer,Integer> entry:valueCountMap.entrySet()) {
int num = entry.getKey();
int value = entry.getValue();
System.out.print(num+":");
for(int i=0;i<value;i++) {
System.out.print("*");
}
System.out.print(" ");
}
}
Following assumptions i have made getData must return interger array and you need to print in one line. Following rectification i have done to your code
in getData i = 0 not i = 1

Related

Sorting array elements and indices, and outputting in table form

The Java program below asks the user for UP TO 25 test scores, it then stores them in an array, averages them, and prints out in table form the inputted test grades as well as the calculated average. There is an unused sorting algorithm present as its own method named selectionSort. This is actually from a textbook.
I need to use that method to sort the array and create an additional output like the second example shown below where the test scores are displayed in ascending order. The only hint I have is that I need to make another array of the indices of the first array.
I'm not supposed to put any additional code in the main method, so I assume I will need a separate method? Or can I put all of the additional code in the selectionSort method so I only have to call one method? All I understand is that the selectionSort method sorts the elements, but not the indices so it won't show Test 1, 2, 3 like it's supposed to. So I need to sort the indices as well, and then somehow print both? How do I do this? Thanks
The current output is like this.
unsorted
I need an additional output like this. "Table of sorted test scores"
sorted
public class ArrayIntro2 {
public static void main(String[] args) {
//integer array
int [] TestGrades = new int[25];
//creating object of ArrayIntro2T
ArrayIntro2T pass = new ArrayIntro2T(TestGrades, 0, 0, 0);
//getting total and filling array
int scoreCount = ArrayIntro2T.FillArray(TestGrades, 0);
//get average score
double avg = pass.ComputeAverage(TestGrades, scoreCount);
//outputting table
ArrayIntro2T.OutputArray(TestGrades,scoreCount,avg);
}
}
//new class to store methods
class ArrayIntro2T{
//variable declaration
double CalcAvg = 0;
int ScoreTotal = 0;
int ScoreCount = 0;
int [] TestGrades = new int[25];
//constructor
public ArrayIntro2T(int [] TestGradesT, int ScoreCountT, double CalcAvgT, int ScoreTotalT)
{
TestGrades = TestGradesT;
ScoreCount = ScoreCountT;
CalcAvg = CalcAvgT;
ScoreTotal = ScoreTotalT;
}
//method to fill array
public static int FillArray(int [] TestGrades, int ScoreCount)
{
Scanner scan = new Scanner(System.in);
System.out.println("Please enter test scores one at a time, up to 25 values or enter -1 to quit" );
TestGrades[ScoreCount]= scan.nextInt();
if(TestGrades[ScoreCount]==-1)
{
System.out.println("You have chosen to quit ");
}
while(TestGrades[ScoreCount]>=0 && ScoreCount<=25)
{
ScoreCount++;
System.out.println("Enter the next test score or -1 to finish ");
TestGrades[ScoreCount] = scan.nextInt();
}
return ScoreCount;
}
//method to compute average
public double ComputeAverage(int [] TestGrades,int ScoreCount)
{
for(int i=0; i<ScoreCount;i++)
{
ScoreTotal += TestGrades[i];
CalcAvg = (double)ScoreTotal/(double)ScoreCount;
}
return CalcAvg;
}
public static void selectionSort(int[] TestGrades){
int startScan, index, minIndex, minValue;
for(startScan=0; startScan<(TestGrades.length-1);startScan++){
minIndex = startScan;
minValue = TestGrades[startScan];
for(index = startScan+1;index<TestGrades.length; index++){
if(TestGrades[index]<minValue)
{
minValue=TestGrades[index];
minIndex=index;
}
}
TestGrades[minIndex]=TestGrades[startScan];
TestGrades[startScan]=minValue;
}
}
//method to output scores and average
public static void OutputArray(int [] TestGrades,int ScoreCount, double CalcAvg)
{
System.out.println("Grade Number\t\tGrade Value");
for(int i=0; i<ScoreCount;i++)
{
System.out.println((i+1)+"\t"+"\t"+"\t"+TestGrades[i]);
}
System.out.printf("Calculated Average\t"+ "%.2f%%", CalcAvg);
}
}
I've tried calling the selectionSort method in the main method, and also using Array.sort although they produce the same result. When I do that, I get an output that looks like this:
failed attempt
Why are you thinking about sorting the indices? The sorted output that you expect doesn't change the order of the indices. Adding the call to selectionSort() in the main method makes sense, but if you're not supposed to do that, you can add it at the end of FillArray(), or the start of OutputArray().
As to the issue with your output, you need to look into sorting only the scores that were entered by the user, and not every entry in the array.

Printing out error messages when user does not input any numbers in array or entering too many numbers into an array

Hello java pros and experts, the first problem I have is implementing a code into my program where it tells a user "No numbers were entered" when they do not enter any numbers and the array is empty.
the second problem I have is implementing a code if the user enters too many numbers, put out an Error message that the size of the array has been exceeded; then print out the numbers entered on the next line.
This is my code so far:
import java.util.Scanner;
public class FunWithArrays
{
public static void main(String[] args)
{
final int ARRAY_SIZE = 10; // Size of the array
// Create an array.
int[] numbers = new int[ARRAY_SIZE];
// Pass the array to the getValues method.
getValues(numbers);
System.out.println("Here are the " + "numbers that you entered:");
// Pass the array to the showArray method.
showArray(numbers);
}
public static void getValues(int[] array)
{
// Create a Scanner objects for keyboard input.
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a series of " + array.length + " numbers.");
// Read the values into the array
for (int index = 0; index < array.length; index++)
{
System.out.print("Enter the number " + (index + 1) + ": ");
array[index] = keyboard.nextInt();
}
}
public static void showArray(int[] array)
{
// Display the array elements.
for (int index = 0; index < array.length; index++)
System.out.print(array[index] + " ");
}
}
I was wondering if you pros or experts have any advice on how to approach this problem without changing any of the codes in my program? my professor instructed me to do a do-while loop for the problem, but do not know how to create the code for it... any suggestions?

Why can't I have a user prompted varaible be the array size?

public class Sort {
public static void main(String[] args) {
int i = 1;
Scanner input = new Scanner(System.in);
// prompts the user to get how many numbers need to be sorted
System.out.print("Please enter the number of data points: ");
int data = input.nextInt();
// this creates the new array and data sets how large it is
int [] userArray = new int[data];
// this clarifies that the value is above 0 or else it will not run
if (data < 0) {
System.out.println("The number should be positive. Exiting.");
}
// once a value over 0 is in, the loop will start to get in all user data
else {
System.out.println("Enter the data:");
}
while (i <= data) {
int userInput = input.nextInt();
userArray[i] = userInput;
i++;
}
// this calls the sortArray method to sort the values entered
sortArray(userArray);
// this will print the sorted array
System.out.println(Arrays.toString(userArray));
}
}
I have set the array size equal to what the user inputs for how many variables they will be entering to be sorted. For some reason, Java only wants a set number instead of the number that is entered by the user. Is there a way to make this work?
First of all, there are a few mistakes in your code. You are checking if(data < 0) after you create your array with int[] userArray = new int[data];. You should check it before.
Furthermore, you will get ArrayIndexOutOfBoundsException because userArray[data] does not exist. Array indices start at 0, so the last index is data-1. You need to change your while-loop to while(i < data) instead of while(i <= data).
The problem is not that you have data instead of 10 as the length of the array. The problem is as I stated above: your while-loop.
Your issue is the while loop. Because arrays are 0 based and you need to only check if i < data. By setting it to <=, you are exceeding the array length and generating and ArrayIndexOutOfBoundsException
while (i < data) {
int userInput = input.nextInt();
userArray[i] = userInput;
i++;
}
You are over-indexing the array. A more standard way for inputting the data would be
for ( int i=0; i < data; i++ ) {
userArray[i] = input.nextInt();
}

Functions/Methods and Arrays

My class has just started learning how to write code in a format with functions and methods, and this is my first attempt at it - I feel like I'm just confusing myself.
The assignment is to create a pool of numbers 1 to a randomly selected number and to store the pool in an array; then print the pool; then a user selects a number from the pool, and the program finds the divisors of that number and stores them in another array that will then be printed.
I am having problems with getting the divisors, storing them in a new array and then printing the array.
import java.util.Scanner;
import java.util.Random;
public class GetDivisors {
public static void main (String[] args){
Scanner read = new Scanner(System.in);
int []pool = new int[100];
int []divisors = new int[100];
int size;
int pick;
int numDivisor;
// Program Heading
printProgramHeading();
// Input and test
size = createPool(pool);
printPool(pool, size);
System.out.println();
System.out.println();
System.out.println("Enter a non-prime value listed in the pool above: ");
pick=read.nextInt();
// Data Processing
numDivisor = getDivisors(pool, divisors, pick);
// Output Section
printDivisors(divisors, size, pick);
} // end main
// Function and Method Specifications
// Name : printProgramHeading
// Description : This method prints the program heading to the monitor in all caps and with a dividing line
// : followed by a blank line.
// Parameters : None.
// Return : None.
public static void printProgramHeading() {
System.out.println("\tGET DIVISORS");
System.out.println(" ************************");
System.out.println();
} // end printHeading
//Name : createPool
//Description : This funtion generates an array of consecutive integers from 1 to a randomly generated
// : number no greater than 100.
//Parameters : An integer array.
//Return : An integer (the randomly generated number), representing the size of the array.
public static int createPool(int[]pool) {
Scanner read = new Scanner(System.in);
Random random = new Random();
int size=0;
size=random.nextInt(100)+1;
pool=new int[size];
return(size);
} // end createPool
//Name : printPool
//Description : This method prints the pool of numbers to the monitor no more than 10 per line.
//Parameters : The pool array, and the size of the pool in that order.
//Return : None.
public static void printPool(int[] pool, int size) {
int index;
int count=0;
for(index=1; index<size; index++){
System.out.print(pool[index]=index);
System.out.print(" ");
count++;
if(count == 10){
System.out.println();
count=0;
} // end if loop
} // end for loop
} // end printPool
//Name : getDivisors
//Description : This funtion stores all the divisors of the user's pick into the divisor array.
//Parameters : The pool array, the divisor array, and the user's pic, in that order.
//Return : The number of divisors found.
public static int getDivisors(int[] pool, int[] divisors, int pick){
int numDivisors = 0;
int index = 0;
for(index=1; index <= pick; index++){
if(pick % index == 0){
numDivisors++;
divisors[index] = index;
} // end if loop
} // end for loop
return(numDivisors);
} // end getDivisors
//Name : printDivisors
//Description : This method prints the contents of the divisors array to the monitor all on one line with
// : a leading label.
//Parameters : The divisor array, an integer representing the number of divisors. and the user's pick
// : in that order.
//Return : None.
public static void printDivisors(int[] divisors, int size, int pick){
int index = 0;
System.out.println("The divisors of " + pick + ": " + divisors[index] + " ");
} // end printDivisors
} // end class
Thank you!
This is obviously a school project. In order for you to learn I don't want to give you the answers but i'll point out your mistakes, so that you can fix your problems.
First in this method createPool:
//Name : createPool
//Description : This funtion generates an array of consecutive integers from 1 to a randomly generated
// : number no greater than 100.
//Parameters : An integer array.
//Return : An integer (the randomly generated number), representing the size of the array.
public static int createPool(int[]pool) {
Scanner read = new Scanner(System.in);
Random random = new Random();
int size=0;
size=random.nextInt(100)+1;
pool=new int[size];
return(size);
} // end createPool
Look closer at the values that are stored in the array.
Second in method printPool:
//Name : printPool
//Description : This method prints the pool of numbers to the monitor no more than 10 per line.
//Parameters : The pool array, and the size of the pool in that order.
//Return : None.
public static void printPool(int[] pool, int size) {
int index;
int count=0;
for(index=1; index<size; index++){
System.out.print(pool[index]=index);
System.out.print(" ");
count++;
if(count == 10){
System.out.println();
count=0;
} // end if loop
} // end for loop
} // end printPool
You are updating the values of the pool. This method should only print the values in the pool. You should be setting the values of the pool in createPool, and printing the values of the pool in printPool.
Next in the getDivisors method
//Name : getDivisors
//Description : This funtion stores all the divisors of the user's pick into the divisor array.
//Parameters : The pool array, the divisor array, and the user's pic, in that order.
//Return : The number of divisors found.
public static int getDivisors(int[] pool, int[] divisors, int pick){
int num = 0;
int divisor = 0;
int numDivisors = 0;
int index = 0;
for(pool[index]=1; pool[index]<=pick; pool[index]){
num = pick % pool[index];
if(num == 0){
divisor = num;
numDivisors++;
divisors= new int[divisor];
} // end if loop
} // end for loop
return(numDivisors);
} // end getDivisors
You have a lot of things wrong with this method. First, re-look at your for loop. I really think you need to learn further about how for loop should operate and when is the best time for use for loops. Your underlying understanding of for loops in flawed. Your logic is right for calculating the divisor, but you have two issues related to this logic. 1) Relook at how you put the new divisor into the divisors array. This is related to the earlier issue of how you use the for loop. Once you solve the for loop problem, this should become more clear 2) What should you store into the divisors array when num == 0 is false? You need to handle this case, right?
Now onto the printDivisors method:
//Name : printDivisors
//Description : This method prints the contents of the divisors array to the monitor all on one line with
// : a leading label.
//Parameters : The divisor array, an integer representing the number of divisors. and the user's pick
// : in that order.
//Return : None.
public static void printDivisors(int[] divisors, int size, int pick){
int index = 0;
System.out.println("The divisors of " + pick + ": " + divisors[index] + " ");
} // end printDivisors
Once again, you really need to understand when and when-not to use a for loop. This method should print out all the values in the divisors array. Currently, this method only prints out one value in the divisors array (the first value, at index 0).
Finally, in the main() function:
public static void main (String[] args){
Scanner read = new Scanner(System.in);
int []pool = new int[100];
int []divisors = new int[100];
int size;
int pick;
int divisor;
// Program Heading
printProgramHeading();
// Input and test
size = createPool(pool);
printPool(pool, size);
System.out.println();
System.out.println();
System.out.println("Enter a non-prime value listed in the pool above: ");
pick=read.nextInt();
// Data Processing
divisor = getDivisors(pool, divisors, pick);
// Output Section
printDivisors(divisors, size, pick);
} // end main
Should int[] pool, and int[] divisors be initialized initially with an arbitrary size of 100? Random numbers like these are usually called "magic numbers". Magic numbers should either be set as a constant with a description, or taken out of the program. Next, you print the header. This seems ok. Then you create the pool, and save the pool size into size, and print the pool with the given size passed into the function. This all seems fine. Next you poll the user for a divisor input, and call the getDivisors function with the user input. Also you save the output into a variable divisor, which represent the size of the divisor array. Now, look at the parameters you pass into printDivisors, something smells fishy here...
These are all of the issues that I see with your code. This should give you plenty of information on how to improve your mistakes. If you have anymore questions please feel free to ask.
Sorry I can't comment your question. Is it ok if you use Collections instead of arrays?
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class GetDivisorsRefactored {
private static Integer[] pool;
private static Scanner read;
public static void main(String[] args) {
// Program Heading
printProgramHeading();
initPool();
System.out.println("Available list: ");
printArray(pool);
read = new Scanner(System.in);
System.out.println();
System.out.println();
System.out.println("Enter a non-prime value listed in the pool above: ");
int pick=read.nextInt();
Integer[] divisors = findDivisors(pick);;
printArray(divisors);
}
private static void printArray(Integer[] someArray) {
int nextRow = 0;
for (int num: someArray){
System.out.printf("%4d,", num);
if (++nextRow > 9){
System.out.println();
nextRow =0;
}
}
}
private static Integer[] findDivisors(int pick) {
List<Integer> divisors = new ArrayList<Integer>();
for (int index = 1; index < pool.length; index++){
if ((pick % pool[index]) == 0){
divisors.add(pool[index]);
}
}
return divisors.toArray(new Integer[divisors.size()]);
}
private static void initPool() {
int size = (int) (Math.random()*100) + 1;
pool = new Integer[size];
for (int index = 0; index < pool.length; index++){
pool[index] = index;
}
}
// Function and Method Specifications
// Name : printProgramHeading
// Description : This method prints the program heading to the monitor in
// all caps and with a dividing line
// : followed by a blank line.
// Parameters : None.
// Return : None.
public static void printProgramHeading() {
System.out.println("\tGET DIVISORS");
System.out.println(" ************************");
System.out.println();
} // end printHeading
}

Java ArrayList: Utilising ArrayList for print message

In my Java program I have an ArrayList. What I want to do is print a number at the bottom that will say 'x amount of people have passed'
System.out.println = ("The amount of people that have more than 40 marks is " + x);
Is it possible to calculate how many numbers of marks will be more than 40 if there are an undetermined amount of marks put in, utilising an ArrayList?
public class test {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
ArrayList<Integer> marks = new ArrayList<Integer>();
Scanner input = new Scanner(System.in);
// Create a new scanner to use in java
int[] range = { 0,29,39,69,100 };
// A new array is created with the grade boundaries
int[] inRange = new int[boundary.length - 1];
// Indexed from 0 to n-1
int markIn;
// New integer markIn
do {
// This do-while loop calculates the expression after the statements below are exectued at least once
System.out.println("Enter Mark(s):");
// Wait for user input
markIn = input.nextInt();
// markInp value is set as the value entered by user
marks.add(markIn);
for (int a=1 ; a<boundary.length ; a++)
// for loop will take the variable 'a' and compare it with varibale 'boundary', when the condition is satisfied that value of 'a' increments by 1
if (range[a-1] <= markInp && markInp <= range[a]) {
// The boundaries will define the upper and lower limits of the markInp
inRange[a-1]++;
//inRange is incremented by 1
break;
//Exit if
}
} while (markIn <= 100);
// When the mark exceeds 100, the loop is stopped
System.out.println(marks);
input.close();
} // Close the Scanner input
}
You can do something like :
int result = 0;
if(marks != null)
{
Collections.sort(marks);
for(int i=0;i<marks.size();i++)
{
if(marks.get(i) > 40)
{
result = marks.size() - i;
break;
}
}
}
marks is the arraylist and result is desired output.
If the array is already sorted, like you show in your example, then you just have to do a simple search from where you start seeing a particular score, then taking the length of the array and subtracting the position of the element that came from your search.
If the array isn't sorted, sort it and then do the search.

Categories