The aim of this exercise is for you to become familiar with compiling, running and debugging Java programs using the basic Sun Java Development Kit. It shows you what a typical program looks like.
Ask the demonstrators to explain aspects of the program that are unfamiliar to you.
Debug the following program:
import java.io.InputStreamReader;
import java.io.IOException;
/**
* A simple guessing game.
*
* @author Andy Wood
* @version BUG-RIDDEN
*
**/
public class Guess
{
private final static int MAX = 10;
public static void main( String argv[] )
{
BufferedReader keyboard = new BufferedReader( new InputStreamReader( System.in ) );
int number;
int guess;
boolean validInput;
System.out.print( "Random Number Program" );
System.out.println( "===================== );
System.out.println();
// choose a random number:
// random.nextFloat returns a number between 0.0 and 1.0
// multiply (*) by MAX to give a number between 0.0 and MAX
// modulo (%) it by MAX to give a number between 0.0 and just under MAX
/ convert it to an int between 0 and MAX - 1
// add one to make it a number between 1 and MAX
nuber = (int)( Math.random() * MAX ) + 1;
System.out.println( "I have thought of a number between 1 and " + number );
System.out.print( "Please enter your guess: " );
do
{
guess = 0
validInput = false;
try
{
String input = keyboard.readLine();
guess = Integer.parseInt( input );
validinput = true;
}
catch ( IOException error )
{
System.err.println( "Error reading from the keyboard: " + error );
System.exit( 1 );
catch ( NumberFormatException error )
{
System.out.print( "Please enter an integer number: " );
}
}
while ( !validInput );
if ( guess = number )
Sytsem.out.println( "Well done - you got it right!" );
else
System.out.println( "Sorry. The number was " + guess );
}
}
/*****************************************************************************/
You should:
Most of the bugs are problems with syntax (mis-spellings, missed out letters/symbols etc.) but some are more serious, in that the program will compile, but may give the wrong or unexpected behaviour. You should aim to solve both.
Remember that sometimes the compiler will complain about errors being on a specific line, when in fact they're often somewhere above it, or just below it, in the code. Also note that fixing one error may fix more than one error message, so recompile if you've just changed something. And finally, if you think that a line may be unnecessary or you really can't see what's wrong with it, then you can comment it out using the // ... or /* ... */ comments, and it should compile.
Try changing the program so that it allows you to have more than one guess at the number. Then, make the computer give you clues if your guess is wrong (e.g. "No! My number is bigger than that!" and "Almost right, but it's a smaller number than that!").
© 2001 Mark Ryan and Alan Sexton