Expand All Collapse All


Bar data type
The compiler says it can’t find Arrays.sort(). What should I do?
Arrays.sort() is in the package java.util.Arrays, so you need to include the following import statement at the beginning of your program.
import java.util.Arrays;
If you use our custom version of IntelliJ, the IDE will automatically add (and remove) the import statement as needed.
How does Arrays.sort() know to call the compareTo() method that I defined?
This mechanism is known as dynamic dispatch. Since Java knows the type of every object, when it is time to compare two objects of type Bar, Java calls the compareTo() method that you implemented in the class Bar.
What happens if I leave out implements Comparable<Bar> in class declaration?
It would lead to a compile-time error if you attempted to call Arrays.sort() with an array of Bar objects. The argument to Arrays.sort() must be an array of comparable objects; otherwise, Java cannot guarantee the existence of the compareTo() method at compile time.
What happens if I include implements Comparable<Bar> but don’t implement the compareTo() method?
It would lead to a compile-time error. By including the code implements Comparable<Bar>, you are promising to implement a method named compareTo() with the specified signature.
BarChartRacer data type
How should I read the data file?
Use the In data type and read the file one line at a time. Call readLine() to read the next line of data and call hasNextLine() to detect whether you have reached the end of the file.
How should I parse each line of data in the data file?
To parse a line containing the number of records in the group, use Integer.parseInt(). To parse a line containing a record, use the split() method from the String library.
My program doesn’t animate things properly. Any advice?
First, make sure that you call StdDraw.enableDoubleBuffering() at the beginning of your program. Then, you should repeatedly read a group of records. When you are done reading a group of records (corresponding to one time period), create the bar chart; clear the screen; draw the bar chart; call StdDraw.show() to display the bar chart on the screen; and call StdDraw.pause(100) to leave the bar chart on the screen for, say, 1/10 of a second. You can adjust the parameter 100 to speed up or slow down the animation.
My program doesn’t use the country field. Is that a problem?
No. While this field is part of the input file format, you will not need that field in this program.
How does BarChart determine which color to color the bars?
It associates each category (e.g., South Asia) with one of 20 predefined colors. If there are more than 20 categories, two entries from two different categories may share the same color.
Curating data sets
Any ideas for curating new data sets?
Yes. You can find lots of animated bar charts on the web. Here are a few starting points: