所以我真的很难格式化我的直方图,让它看起来像我们需要做的。我完全迷失和沮丧,因为我无法让它看起来像所要求的直方图。这是我们说明的链接,那里有一张关于它应该是什么样子的图片,我不能在这里放图片,因为我没有足够的声誉,但这里是链接:http://www。 cs.plu.edu/courses/csce144/fall2013/labs/lab07/RandomNumberTesting.html 提前感谢您的帮助!
import java.util.Scanner; // to be able to read from the keyboard
public class RandomNum
{
/*
Method 1:
Find the maximun value in an array
*/
public static int max(int[]arr){
int maxValue = arr[0];
for ( int i=1; i < arr.length; i++ ){
if (arr[i] > maxValue){
maxValue = arr[i];
}
}
return maxValue;
}
/*
Method 2:
Compute a random integer in the range [a..b)
*/
public static int randomInteger(int a, int b){;
int randomNum;
randomNum = (int)(Math.random() * (b+1-a) + a);
return randomNum;
}
/*
Method 3:
Draw a Simple histogram of the array arr.
*/
public static void drawHistogram(int[] arr){
for ( int i=max(arr); i>0; i--){
System.out.print(i + "\t");
for (int j=0; j<arr.length; j++){
if ( arr[j] >= i){
System.out.print("x");
}else {
System.out.print(" ");
}if ( j%10 == 0 && j!=0){
System.out.print(" ");
}
}System.out.println();
}
for (int i=0; i<=arr.length; i++){
if ( i == 0){
System.out.print("\t\t");
}if ( i%10 == 0 && i != 0){
System.out.print(i + " ");
}
}System.out.println();
}
/*
Method 4:
Compute num random integers in the range [0..range) and put the frequency in arr[]
*/
public static void doSingleTest(int[] arr, int num, int range){
for (int i=1; i<=num; i++){
int random = randomInteger(0,range);
arr[random]++;
}
}
/*
Method 5:
Compute num pairs of random integers in the range [0..range) and put the frequency in arr[]
*/
public static void doPairsTest(int[] arr, int num, int range){
int rangeA = range/10;
int rangeB = range%10;
for (int i=1; i<=num; i++){
int random = ((randomInteger(0,rangeA) * 10) + randomInteger(0,rangeB));
arr[random]++;
}
}
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
// declarations
int num;
// histogram presentation
System.out.println("Enter the amount of pairs you want to test: ");
num = keyboard.nextInt();
int[] arr = new int[100];
doPairsTest(arr, num, 99);
drawHistogram( arr );
}
}