Here are our sample solutions.
public void printHashMarks(int version)
{
// The numbers of classes in versions
// 1.0, 1.1, 1.2, 1.3 and 1.4 of Java
// in units of one hundred.
int[] classes = {2, 5, 18, 21, 30};
// print as many hash marks as there are hundreds
// of classes for the version
for (int j = 0; j < classes[version]; j++)
{
System.out.print("#"); //print on the same line
}
System.out.println(); // print a single newline character
}
This method's job is to print as many # marks as there are classes in the version (received as an argument)
The key point about this method is that it uses the array element at classes[version] to decide how many hash marks to print in the for loop. Inside the loop we use a print statement (rather than a println statement) so that each hash mark appears on the same line. Other conditions are possible to control the loop, for example, we could start j at 1 and count to j <= classes[version].
There are various ways to print the single newline character we require after the hash marks. You could also use System.out.print("\n").
for (int i = 0; i < labels.length; i++)
{
//First we print the label and axis.
System.out.print(labels[i] + "\t|");
// Then we print the hash marks for this version
printHashMarks(i);
//After each bar is plotted, we draw another piece of axis
//following it by a newline character
System.out.println("\t|");
}
The stopping condition of the loop uses the length of the labels array to decide how
many labels to print. We make the array index i
start at 0, because
array indexing in Java is from 0. The last position in the array is at
labels[labels.length - 1]
Unit
2/Ex2_7/build/classes):java ex2_7.Main2. An alternative approach is to use a different method to format the output, such as the
System.out.format method. An
example plotGraph method is shown below using this
approach. Please note that understanding of this approach is not part of the course:public void plotGraph()
{
// Labels for successive versions of the Java Standard Edition API.
String[] labels =
{
"1.0", "1.1", "1.2", "1.3", "1.4"
};
// A legend for the horizontal graph axis.
String legend = "Hundreds of classes in successive versions of Java";
// Print a blank line, to give some space above the graph
System.out.println();
for (int i = 0; i < labels.length; i++)
{
//the %10s indicates how much space to use for the following string
System.out.format("%10s", labels[i] + "|");
// Then we print the hash marks for this version
printHashMarks(i);
}
//When all the bars are printed, we plot the horizontal axis.
//This bar is 50 characters long, and the labels occupied 10 characters
//so here we used 60 characters width for the printout
System.out.format("%60s", "|----|----|----|----|----|----|----|----|----|----|");
//Finally we print the legend.
System.out.format("%60s", "\n\n\t" + legend + "\n");
}