Write a program Odometer.java
that displays on screen an odometer that counts up from 0000
to 9999
. Although you could write this as a single loop that runs from 0 to 9999, we'd have to figure out a way to print out those leading zeroes. Instead, write the program as a series of nested loops, one for the ones place, one for the tens place, one for the hundreds place, and one for the thousands place.
As part of this activity you may find it convenient to clear the Terminal window. The following code may do that:
/**
* The clearConsole method attemps to clear the Terminal so that
* successive generations of the board can be displayed. The ANSI
* escape sequence printed here only works in Terminals that support
* them. BlueJ doesn't, but if you run this code in a regular
* Terminal window, it might work!
*/
private static void clearConsole()
{
try {
System.out.print("\033[H\033[2J");
System.out.flush();
}
catch (Exception exception)
{
System.out.println("Error");
// Handle exception.
}
}
You may also find it convenient to slow your loop down by having it sleep for some period of time. In this try-catch statement, milliseconds represents how long you want the program to pause for.
public static void sleep(int milliseconds)
{
try
{
Thread.sleep(milliseconds);
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
}
}
Here's a hint on how I did it. See if you can fill in the missing lines of code to make it work.
/**
* Write a program that displays on screen an odometer that
* counts up from 0000 to 9999.
*
* @author Richard White
* @version 2018-08-07
*/
public class Odometer
{
/**
* The clearConsole method attemps to clear the Terminal so that
* successive generations of the board can be displayed
*/
private static void clearConsole()
{
try {
System.out.print("\033[H\033[2J");
System.out.flush();
}
catch (Exception exception)
{
System.out.println("Error");
// Handle exception.
}
}
private static void sleep(int ms)
{
try
{
Thread.sleep(ms);
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
}
}
public static void main(String[] args)
{
// Nested loop code lines goes here
{
clearConsole();
System.out.print(thousands +"" + hundreds + "" + tens + "" + ones);
sleep(500);
}
}
}