Java

TOPIC 20 – WHILE LOOPS – Part 2

 

LESSON WORK

 

 

QUESTION 1

Write a Guess The Number program.

The program starts by generating a random integer between 0 and 1000.  It then continually asks the user to guess the number and outputs whether the guess is too low, too high or correct.  If the guess is correct, the program should output an appropriate message and terminate.

 

Sample output:

 

     Please guess a number between 0 and 1000.

     400

     Your guess is too high.

 

     Please guess another number.

     150

     Your guess is too low.

 

     Please guess another number.

     240

     Your guess is too high.

 

     Please guess another number.

     220

     Your guess is too low.

 

     Please guess another number.

     234

     Your guess is too low.

 

     Please guess another number.

     237

     You guess is too high.

 

     Please guess another number.

     236

     You got it right!

 

Extra: Can you add the code required to include the total number of guesses needed to guess the correct number?

 

QUESTION 2

 

Write a program that will continuously get a mark (from 0 to 100) from the user. If the value -1 is entered, the program calculates the average of the mark and outputs it to screen. If any other illegal value is entered, it should be ignored (display error message) and the program should continue to wait for another mark.

 

Remember that the -1 should not be part of the average’s calculation.

 

Sample output:

 

     Enter a mark:

     80

     Enter a mark:

     70

     Enter a mark:

     90

     Enter a mark:

     -1

     Your average is 80.