Java直方图
发布网友
发布时间:2022-05-18 03:01
我来回答
共1个回答
热心网友
时间:2023-10-08 15:14
import java.util.Arrays;
import java.util.Scanner;
public class Histogram{
private String title;
private double start, stop;
private double[] data;
public Histogram(String title, double start, double stop, double[] data, int numBars){
this.title = title;
this.start = start;
this.stop = stop;
this.data = data;
}
public String toString(){
int len = data.length;
String[] arr = new String[len];
double tmp = start;
double each = (stop - start) / (len - 1);
double max = Double.MIN_VALUE;
for(int i = 0; i < len; i++)
{
double di = data[i];
max = di > max ? di : max;
}
for(int i = 0; i < len; i++)
{
String x = "";
int num = Integer.parseInt(String.format("%.0f", data[i] * 40 / max));
for(int j = 0; j < num; j++)
{
x += "#";
}
arr[i] = tmp + " " + x + " " + data[i];
tmp += each;
}
return String.format("%s%s20^", title,
Arrays.toString(arr).replaceAll("\\x20", "")
.replaceAll("[\\[\\],]", "\r\n"));
}
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("Enter a histogram.");
System.out.println("Title: ");
String title = scan.nextLine();
System.out.println("Start value: ");
double start = Double.parseDouble(scan.nextLine());
System.out.println("End value: ");
double stop = Double.parseDouble(scan.nextLine());
System.out.println("Data: ");
String d = scan.nextLine();
scan.close();
String[] ds = d.split("\\s+");
double[] data = new double[ds.length];
for(int i = 0; i < data.length; i++){
data[i] = Double.parseDouble(ds[i]);
}
Histogram hist = new Histogram(title, start, stop, data, data.length);
System.out.println(hist.toString());
}
}