publicclassBarimplementsComparable<Bar>{privateString name;privateint value;privateString category;// Creates a new bar.publicBar(String name,int value,String category){if(name ==null){thrownewIllegalArgumentException("name is null");}if(value <0){thrownewIllegalArgumentException("value is negative");}if(category ==null){thrownewIllegalArgumentException("category is negative");}this.name = name;this.value = value;this.category = category;}// Returns the name of this bar.publicStringgetName(){return name;}// Returns the value of this bar.publicintgetValue(){return value;}// Returns the category of this bar.publicStringgetCategory(){return category;}// Compare two bars by value.publicintcompareTo(Bar that){if(that ==null){thrownewNullPointerException();}returnthis.value - that.value;}// Sample client (see below).publicstaticvoidmain(String[] args){}}
BarChartRacer.java(超级火的动态可视化条形图,实现起来挺简单的)
importjava.util.Arrays;publicclassBarChartRacer{publicstaticvoidmain(String[] args){// 从命令行参数获取文件和条形个数kString filename = args[0];int k =Integer.parseInt(args[1]);// 读取文件In in =newIn(filename);String title = in.readLine();String xAxisLabel = in.readLine();String dataSource = in.readLine();// 该对象用于后面的绘制BarChart barChart =newBarChart(title, xAxisLabel, dataSource);StdDraw.setCanvasSize(1000,700);StdDraw.enableDoubleBuffering();StdAudio.loop("soundtrackB.wav");while(in.hasNextLine()){
in.readLine();int n =Integer.parseInt(in.readLine());String date ="";Bar[] bars =newBar[n];for(int i =0; i < n; i++){String line = in.readLine();String[] arr = line.split(",");
date = arr[0];String name = arr[1];String country = arr[2];int value =Integer.parseInt(arr[3]);String category = arr[4];
bars[i]=newBar(name, value, category);}Arrays.sort(bars);
barChart.reset();
barChart.setCaption(date);// 只绘制最大的k个条形for(int i = n -1; i >= n - k; i--){
barChart.add(bars[i].getName(), bars[i].getValue(), bars[i].getCategory());}// draw the bar chartStdDraw.clear();
barChart.draw();StdDraw.show();StdDraw.pause(100);}}}
Here is the original linkBar.java(条形类,实现了Comparable接口,主要用于排序)public class Bar implements Comparable<Bar> { private String name; private int value; private String category; // Creates a new bar. public Bar(String name, in