Hi I have been given a problem to complete over two practicals. I have had one and got nowhere really with it. Here is the problem:
Exercises 3 and 4. Write a Java program to
1. Read three integers, say n, bottom and top, from the input stream;
2. Read n ‘double’ numbers and count how many of them fall in each of the intervals (-,bottom), (bottom,bottom+1), ..., (top-1,top), (top,); store these counts (frequencies) in an array with top-bottom+2 elements;
3. Display the observed frequencies in a histogram, using an appropriate number of ‘*’ for each (horizontal) bar. For example, if n is 20, bottom is 1, top is 4, and the observed frequencies are 5, 0, 8, 3, 4, the histogram may appear as follows (you can decide how to label the bars, and what title or caption to include):
(-inf,1) | *****
(1,2) |
(2,3) | ********
(3,4) | ***
(4,inf) | ****
Exercise 3 consists of steps 1 and 2 above (print the resulting array); exercise 4 is step 3.
Now the code which I have done already i will post below. The problem I have is I cant figure out whether to use a while loop or a for loop, and really cant figure out how to do it. I am getting to the stage where it would really help if someone could just post the actual loop as I have worked for a long time on this and cant get my head round it. After that is done, just a pointer to the histogram would do, as I think i can manage that bit. Thanks for you help.
Andy
Code:
import java.io.*;
import javagently.*;
public class Frequency
{
public static void main() throws IOException
{
Stream input = new Stream(System.in);
int n; //Stores how many numbers to be inputted
int bottom, top; // Stores top and bottom numbers
int i; // Used for loop variables
System.out.println("How many numbers would you like to input?");
n = input.readInt();
System.out.println("Please choose a high number");
top = input.readInt();
System.out.println("Please choose a low number");
bottom = input.readInt();
int [] freq = new int [top-bottom+2]; //Gives number of intervals
for (int i = 0 ; i < top-bottom+2 ; i++)
freq [i] = 0;
for(i=0; i < n ; i++)
System.out.println("Please input the first number");
freq [i] = input.readDouble();//Read next number of type double
while ( i <= bottom)
{
freq [0]++;
}
}
}
}
As I said I think i have gone wrong somewhere and am getting all confused. If someone could help me out, that would be great.
Andy