Welcome to Dream.In.Code
Become a Java Expert!

Join 150,058 Java Programmers for FREE! Get instant access to thousands of Java experts, tutorials, code snippets, and more! There are 1,728 people online right now. Registration is fast and FREE... Join Now!




Histogram

 
Reply to this topicStart new topic

Histogram, printing out a histogram both manually and Gaussian

mds913
5 Jun, 2008 - 06:32 PM
Post #1

New D.I.C Head
*

Joined: 5 Jun, 2008
Posts: 18

Hi,

I'm trying to complete this project but have a few unsettled issues. Breif overview: The code involves using arrays and next Gaussian to create a histogram of student test scores. I have the majority of the code completed.

Here's where it gets hung up. After the manual entry of the scores (generateUser metod)the histogram is suppose to print out. I can unit test the histogram and it works fine. what i just can't seem to understand is what is supposed to happen after the scores are input. i'm guessing that the line :scores = generateUser(students); is supposed to execute and then print the histogram. i just can't get it.

Secondly, at: grade = generator.nextGaussian(); i get a possible loss of precision error. i have Grade as an int which i thought was acceptable(although i think i should probably have it as a double). anyway, enough of my blabbing. can anyone help?


import javax.swing.*;
import java.util.*;



public class histogramArray
{
public static void main(String[]args)
{
int students;

String numStudents;
String posNumber;
String inputOrRandom=null;
String answer;

numStudents = JOptionPane.showInputDialog("How many students in the class?");
students = Integer.parseInt(numStudents);

while(students < 0)
{
posNumber = JOptionPane.showInputDialog("Please enter a positive number.");
students = Integer.parseInt(posNumber);
}
if(students > 0)
inputOrRandom = JOptionPane.showInputDialog("Would you like to input the numbers or have them random generate? (I/R) ");

if(inputOrRandom.equals("I") || inputOrRandom.equals("i"))
scores = generateUser(students); //System.out.print("III");

else if
(inputOrRandom.equals("R") || inputOrRandom.equals("r"))
generateRandom(students); //System.out.print("RRR");

else
return;

}


public static int[]generateUser(int k)
{
Scanner console = new Scanner(System.in);

int [] scores = new int[10];
String giveNumberStr = null;
int giveScoreInt = 0;

for(k = 0; k < scores.length; k++)//sets scores to be 0 in the array.
scores[k] = 0;

for(k = 0; k < scores.length; k++)//counter returns to ask for next score from user.

{
giveNumberStr = JOptionPane.showInputDialog("Please enter an integer between 1 and 100.");
giveScoreInt = Integer.parseInt(giveNumberStr);//grabs input of integer between 1 and 100.

while(giveScoreInt < 1 || giveScoreInt > 100)
{
giveNumberStr = JOptionPane.showInputDialog("You entered " +giveScoreInt+ " which is outside the range. Please resubmit score");
giveScoreInt = Integer.parseInt(giveNumberStr);

}

System.out.print(+giveScoreInt+ " ");
{
if (giveScoreInt >= 1 && giveScoreInt <=10) //these all load the array based on the user input of scores.
scores[0]++;
if(giveScoreInt >= 11 && giveScoreInt <= 20)
scores[1]++;
if(giveScoreInt >= 21 && giveScoreInt <= 30)
scores[2]++;
else
if(giveScoreInt >= 31 && giveScoreInt <= 40)
scores[3]++;
else
if(giveScoreInt >= 41 && giveScoreInt <= 50)
scores[4]++;
else
if(giveScoreInt >= 51 && giveScoreInt <= 60)
scores[5]++;
else
if(giveScoreInt >= 61 && giveScoreInt <= 70)
scores[6]++;
else
if(giveScoreInt >= 71 && giveScoreInt <= 80)
scores[7]++;
else
if(giveScoreInt >= 81 && giveScoreInt <= 90)
scores[8]++;
else
if(giveScoreInt >= 91 && giveScoreInt <= 100)
scores[9]++;

}

}//at this point the counter goes back up to get the i next integer from user.

//scores = generateUser(students);//(

return scores;

}

public static int [] generateRandom(int numOfStudents)
{
Random generator = new Random();
int i=0;
int [ ] scores = new int[10];
int grade;



for(int j = 0; j < 10; ++j)
scores[j] = 0;

for(i = 0; i < numOfStudents; i++)
{
grade = generator.nextGaussian();
grade = Math.min(1,grade);
grade = Math.max(100,grade);

scores[(grade-1)/10]= scores[(grade-1)/10]+1;
System.out.print(grade + " ");
}
System.out.println();
return scores;


}

public static void outputHistogram(int[] scores)
{
String again;
for(int i = 0; i < 10; ++i)//set up counter for printing the labels, i.e 1-10, 11-21, etc.,
{
if(i == 0)
System.out.print((i*10 + 1)+" -"+(i*10+10)+ " |");
if(i >= 1 && i <= 9)
System.out.print((i*10 + 1)+"-"+(i*10+10)+ " |");//this prints the labels 1-10,11-21, etc.
if(i == 10) // else
System.out.print((i*10 + 1)+"-"+(i*10+10)+ "|");//this prints out and lines up the 91-100 row.

for(int j = 0; j < scores[i]; ++j) //this nested loop will connect the value in scores[] to the "*" that print out.
System.out.print("*");

System.out.println();

again = JOptionPane.showInputDialog("Would you like to try again?");// this is return code
if (again == "N" || again == "n") // this is return code
System.exit(0); // this is return code
else // this is return code

return; // this is return code

}
//return;
}
}

User is offlineProfile CardPM
+Quote Post

pbl
RE: Histogram
5 Jun, 2008 - 06:47 PM
Post #2

D.I.C Lover
Group Icon

Joined: 6 Mar, 2008
Posts: 3,587



Thanked: 233 times
Dream Kudos: 75
My Contributions
Kind of strange code here....
Please use this to post your code code.gif

by the way your code does not compile so don't bother if it does not do nothing

CODE

    numStudents = JOptionPane.showInputDialog("How many students in the class?");
    students = Integer.parseInt(numStudents);

OK you ask for the number of students and store the result into the variable students

CODE


    while(students < 0)
    {
        posNumber = JOptionPane.showInputDialog("Please enter a positive number.");
        students = Integer.parseInt(posNumber);
    }


Here you will prompt for a positive number
Assign that number to the variable students
OK user can enter 10, 20, 30, 40, 50,...... and finally -1

CODE

    if(students > 0)
        inputOrRandom = JOptionPane.showInputDialog("Would you like to input the numbers or have them random generate? (I/R) ");


If you exited the loop it is because students is < 0 so this condition will never be true

CODE

    if(inputOrRandom.equals("I") || inputOrRandom.equals("i"))
        scores = generateUser(students); //System.out.print("III");


as if(students > 0) will never be true inputOrRandom will be equals to null as you initialized it
this if is useless
by the way "scores" is not defined

no need to go to the else clause that follows... inputOfRandom is null

Did you cut&paste this code and try to make it work ?

This post has been edited by pbl: 5 Jun, 2008 - 06:48 PM
User is online!Profile CardPM
+Quote Post

mds913
RE: Histogram
5 Jun, 2008 - 07:36 PM
Post #3

New D.I.C Head
*

Joined: 5 Jun, 2008
Posts: 18

It would probably help make more sense if i included the directions. would that be ok?
User is offlineProfile CardPM
+Quote Post

pbl
RE: Histogram
5 Jun, 2008 - 07:43 PM
Post #4

D.I.C Lover
Group Icon

Joined: 6 Mar, 2008
Posts: 3,587



Thanked: 233 times
Dream Kudos: 75
My Contributions
QUOTE(mds913 @ 5 Jun, 2008 - 08:36 PM) *

It would probably help make more sense if i included the directions. would that be ok?

Would make more sens if you post code that works following the rules
code.gif
and explain what is your concern
- code does not compile
- application does not have the behaviour I expected ( prints "that" when I think it should print "this")

and for sure

Dream.In.Code has a policy by which we prefer to see a good faith effort on your part before providing source code for homework assignments. Please post the code you have written in an effort to resolve the problem, and our members would be happy to provide some guidance. Be sure to include a description of any errors you are encountering as well.

Please post like this:

Thank you for helping us helping you.

User is online!Profile CardPM
+Quote Post

mds913
RE: Histogram
5 Jun, 2008 - 07:49 PM
Post #5

New D.I.C Head
*

Joined: 5 Jun, 2008
Posts: 18

Objective of this Program: (1) To learn more about using arrays, but only of primitive type (ints), (2) to get some more experience using Java API, namely the class Random, and (3) to use the for construct.


Basic Problem
We are given a collection of scores for a class, and we want to create a histogram of the scores, where we divide the scores into dectiles. So, for example, if the scores for the class were 33, 35, 53, 59, 66, 70, 72, 82, 82, 84, 86, 89, 90, 90, 93, 95, 96, 100, the histogram would look like:

1 - 10:
11 - 20:
21 - 30:
31 - 40:**
41 - 50:
51 - 60:**
61 - 70:**
71 - 80:*
81 - 90:******
91 -100:****

Furthermore, we will generate the scores for the class by one of two means: (1) ask the user to input the scores and (2) have the computer randomly generate the scores.

So what this program will do is ask the user for the number of students in the class. Then it will ask the user if they want to input the numbers or have the computer generate the scores randomly. Then having the scores, it will output them in a histogram.

Since we want to output the scores via dectiles, we will need an array of size 10. One creates an array of size to via

int [] scores = new int[10];

Each value of scores[i] will record the scores from i*10 to i*10+9.

We will do this by creating a class ClassHistogram, which will have 4 methods: (1) main, (2) generateUser , generateRandom, and outputHistogram.

The abstract data type or ADT of this class can be found here. Its Universal Markup Language or UML version can be found here.


main method
The main method will do the following:

Create the array of scores of size 10.
Ask the user via JOptionPane for the number of students in the class
If the number is positive then
Ask the user if the user or computer is inputing data
Call the appropriate method for input
call the method outputHistogram to show the histogram
If the number is non-positive, tell the via JOptionPane the data must be positive
Ask the user is they want to continue

generateUser and generateRandom methods
The protocol for these two methods are the same:

public static int [] generateUser(int n)

public static int [] generateRandom(int n)

The input parameter is the number of students in the class. The value returned is the array which is created with the values stored in it.

They each will get a score from 1 to 100 and increment the corresponding value of scores[i]. The generateUser will ask for the input, while the generateRandom will generate them at random using the class Random. See below on how to do this.

Note: For user input be sure to check if the input is between 1 and 100. If not, notify the user. Make sure that you get n good inputs.

Note: For the computer generated input, you will have to create an object of the class Random. See below on how to do this.

Hint: For the input value of integer k, what is the value of (k-1)/10?

outputHistogram method
The protocol for this method is:

public static void outputHistogram(int [] scores)

This method will output the histogram. For each i in the dectile, it will first output the label (e.g., 11 - 21), and then put out an '*' for each value in the corresponding scores value. Note that for the example above, the values of scores[0] = scores[1] = scores[2] = scores[4] = 0, scores[7] = 1, scores[3] = scores[5] = scores[6] = 2, scores[9] = 4, and scores[8] = 7.

You will do this with two nested for loops. Be sure to put in a System.out.println() (a carriage return) at the end of the nested inner for loop.


Random class
The Random class is found in java.util.random, so you will have to import this class. The details of this class can be found at Random class.

One creates an object of the class via the constructor:

Random generator = new Random();

The method nextGaussian will generate a random number with mean of 0 and standard deviation of 1.0. The distribution is the Gaussian or normal distribution, the famous "bell shaped curve". You want to modify this value to be between 1 and 100.

To say it has a standard deviation of 1, means that 67% of the values will be between -1 and +1. That 95% of the values will be between -2 and +2, that 99.6% of the values will be between -3 and +3. So FOR ALL PRACTICLE PURPOSES, we can assume that the range of values are between -3 and +3. So you must "stretch" these values to be between 1 and 100.

One way to do this is to add a constant c to the returned value, which now gives a value between -3+c and 3+c. Then multiply it by an appropriate constant to get it between 0 and 100. Finally truncate it at one to get rid of the rare case of having a value less than 1. Also truncate it at 100 to get rid of the rare case of having a value more than 100.

Note:You truncate it at 1, by using the function Math.max() with one of the values being the generated value, and the other being the value of 1. Math.max(1,u) will return a value of at least 1. You truncate it at 100 by using the Math.min().

Note:The constant of c equal to 3 will make the median score 50. If you want a median score of 75, what would you do?

Do an incremental development as you did in program 5. An outline of an incremental development is given here


sorry about posting the code incorrectly. here it is:

CODE

import javax.swing.*;
import java.util.*;



public class histogramArray
{
    public static void main(String[]args)
    {
       int students;
      
       String numStudents;
       String posNumber;
       String inputOrRandom;
       String answer;
      
        numStudents = JOptionPane.showInputDialog("How many students in the class?");
        students = Integer.parseInt(numStudents);
        
        while(students < 0)
        {
            posNumber = JOptionPane.showInputDialog("Please enter a positive number.");
            students = Integer.parseInt(posNumber);
        }
            if(students > 0)
            inputOrRandom = JOptionPane.showInputDialog("Would you like to input the numbers or have them random generate? (I/R) ");
            
            if(inputOrRandom.equals("I") || inputOrRandom.equals("i"))
            scores = generateUser(students);  //System.out.print("III");
                        
            else if
            (inputOrRandom.equals("R") || inputOrRandom.equals("r"))
            generateRandom(students);  //System.out.print("RRR");
            
            else
            return;
            
        }

        
    public static int[]generateUser(int k)
    {
        Scanner console = new Scanner(System.in);
        
        int [] scores = new int[10];
        String giveNumberStr = null;
        int giveScoreInt = 0;
                
        for(k = 0; k < scores.length; k++)//sets scores to be 0 in the array.
        scores[k] = 0;
        
        for(k = 0; k < scores.length; k++)//counter returns to ask for next score from user.
        
        {
        giveNumberStr = JOptionPane.showInputDialog("Please enter an integer between 1 and 100.");
        giveScoreInt = Integer.parseInt(giveNumberStr);//grabs input of integer between 1 and 100.
        
        while(giveScoreInt < 1 || giveScoreInt > 100)
        {
        giveNumberStr = JOptionPane.showInputDialog("You entered " +giveScoreInt+ " which is outside the range. Please resubmit score");
        giveScoreInt = Integer.parseInt(giveNumberStr);
        
        }
        
        System.out.print(+giveScoreInt+ " ");
        {
        if (giveScoreInt >= 1 && giveScoreInt <=10)     //these all load the array based on the user input of scores.
        scores[0]++;
        if(giveScoreInt >= 11 && giveScoreInt <= 20)
        scores[1]++;
        if(giveScoreInt >= 21 && giveScoreInt <= 30)
        scores[2]++;
        else
        if(giveScoreInt >= 31 && giveScoreInt <= 40)
        scores[3]++;
        else
        if(giveScoreInt >= 41 && giveScoreInt <= 50)
        scores[4]++;
        else
        if(giveScoreInt >= 51 && giveScoreInt <= 60)
        scores[5]++;
        else
        if(giveScoreInt >= 61 && giveScoreInt <= 70)
        scores[6]++;
        else
        if(giveScoreInt >= 71 && giveScoreInt <= 80)
        scores[7]++;
        else
        if(giveScoreInt >= 81 && giveScoreInt <= 90)
        scores[8]++;
        else
        if(giveScoreInt >= 91 && giveScoreInt <= 100)
        scores[9]++;
      
        }
      
        }//at this point the counter goes back up to get the i next integer from user.
        
        //scores = generateUser(students);//(
        
        return scores;
                
    }
    
     public static int [] generateRandom(int numOfStudents)
    {
        Random generator = new Random();
        int i=0;
        int [ ] scores = new int[10];
        int grade;
        
        
        
       for(int j = 0; j < 10; ++j)
            scores[j] = 0;
          
        for(i = 0; i < numOfStudents; i++)
        {
            grade = generator.nextGaussian();
            grade = Math.min(1,grade);
            grade = Math.max(100,grade);
            
            scores[(grade-1)/10]= scores[(grade-1)/10]+1;
            System.out.print(grade + " ");
        }
       System.out.println();
        return scores;


    }
    
    public static void outputHistogram(int[] scores)
    {
        String again;
        for(int i = 0; i < 10; ++i)//set up counter for printing the labels, i.e 1-10, 11-21, etc.,
            {
            if(i == 0)
                System.out.print((i*10 + 1)+" -"+(i*10+10)+ "  |");
            if(i >= 1 && i <= 9)
                System.out.print((i*10 + 1)+"-"+(i*10+10)+ "  |");//this prints the labels 1-10,11-21, etc.
             if(i == 10)  // else
                System.out.print((i*10 + 1)+"-"+(i*10+10)+ "|");//this prints out and lines up the 91-100 row.
                                
            for(int j = 0; j < scores[i]; ++j)       //this nested loop will connect the value in scores[] to the "*" that print out.
            System.out.print("*");
            
            System.out.println();
            
            again = JOptionPane.showInputDialog("Would you like to try again?");// this is return code
            if (again == "N" || again == "n")                                   // this is return code            
            System.exit(0);                                                     // this is return code
            else                                                                // this is return code
            
            return;                                                             // this is return code
  
        }
        //return;
}
}

User is offlineProfile CardPM
+Quote Post

pbl
RE: Histogram
5 Jun, 2008 - 08:18 PM
Post #6

D.I.C Lover
Group Icon

Joined: 6 Mar, 2008
Posts: 3,587



Thanked: 233 times
Dream Kudos: 75
My Contributions
java

public class ScoreArray {

// constructor that receives an array of scores
ScoreArray(int[] values) {
// ok how many of every thing ranks by 10
int[] nbEach = new int[10];
// constructor that receives an array of score
for(int i = 0; i < values.length; i++)
nbEach[values[i]/10]++;
// ok I built my array now let's print it whith an histotogram
for(int i = 0; i < nbEach.length; i++) {
System.out.print("[" + i + "] = " + nbEach[i] + " ");
for(int j = 0; j < nbEach[i]; j++)
System.out.print("*");
System.out.println();

}
}

public static void main(String[] arg) {
int[] score = { 10, 20, 22, 25, 30, 40, 10, 18, 16, 77, 66, 18, 92, 17, 11, 22};
new ScoreArray(score);
}
}


This post has been edited by pbl: 6 Jun, 2008 - 08:20 AM
User is online!Profile CardPM
+Quote Post

fsloke
RE: Histogram
6 Jun, 2008 - 04:52 AM
Post #7

D.I.C Regular
***

Joined: 19 Dec, 2007
Posts: 258



Thanked: 4 times
My Contributions
Please go to buy Deitel & Deitel Java Book

The solution is inside the book.

You array can shorten your coding.

Display it using the contain inside the array that store.

Key: Array + For loop
User is offlineProfile CardPM
+Quote Post

pbl
RE: Histogram
6 Jun, 2008 - 08:26 AM
Post #8

D.I.C Lover
Group Icon

Joined: 6 Mar, 2008
Posts: 3,587



Thanked: 233 times
Dream Kudos: 75
My Contributions
oups... forgot to use a Random generator

java

import java.util.Random;

public class ScoreArray {

// constructor that receives an array of scores
ScoreArray(int[] values) {
// ok how many of every thing ranks by 10
int[] nbEach = new int[10];
// constructor that receives an array of score
for(int i = 0; i < values.length; i++)
nbEach[values[i]/10]++;
// ok I built my array now let's print it whith an histotogram
for(int i = 0; i < nbEach.length; i++) {
System.out.print("[" + i + "] = ");
// print an extra " " if nbEach < 10
if(nbEach[i] < 10)
System.out.print(" ");
System.out.print(nbEach[i] + " ");
for(int j = 0; j < nbEach[i]; j++)
System.out.print("*");
System.out.println();
}
}

public static void main(String[] arg) {
// random generator
Random r = new Random();
int[] score = new int[100];
// generate 100 numbers between 0 and 99
for(int i = 0; i < score.length; i++)
score[i] = r.nextInt(100);
new ScoreArray(score);
}
}

User is online!Profile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic
Time is now: 1/8/09 10:34PM

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter

Live Java Help!

Java Tutorials

Reference Sheets

Java Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month