Unit 04 Wed - Iteration
Homework
Part 1 - Find on the bottom of the Jupyter Notebook linked on slide 2
Choose ONE
Write a program where the user inputs their monthly budget. The loop should then ask the user to input each of their monthly expenses. These expenses should be kept in a running total. The final output should display if the user is over or under their budget for the month, and by how much.
Write a program where a random number is generated. Then the user tries to guess the number. If they guess too high display something to let them know, and same for if they guess a number that is too low. The loop must iterate until the number is guessed correctly.
import java.util.Scanner;
import java.util.Random;
public class NumberGuessingGame {
public static void main(String[] args) {
int randomNumber, userNumber = 0;
final int MAX = 100;
char playGame = 'y';
Random generator = new Random();
// ask user if they wish to play
System.out.println("Would you like to play the Number Guessing y / n");
Scanner scan = new Scanner(System.in);
playGame = scan.next().charAt(0);
//The loop controlling the game
while (playGame == 'y') {
if (playGame != 'y')
break;
randomNumber = generator.nextInt(MAX) + 1;
//Creating a flag to control the inner loop
int correct = 0;
//The loop to control the round.
while (correct == 0){
System.out.println("Please pick a number between 1 and 100");
userNumber = scan.nextInt();
// high and low sugguestion
if (userNumber > randomNumber)
System.out.println("Number is too high, try something lower.\n");
if (userNumber < randomNumber)
System.out.println("Number is too low, try something higher.\n");
if (userNumber == randomNumber) {
System.out.println(randomNumber + " number is correct!");
System.out.println("Thank you for playing!");
correct = 1;
}
}
}
}
}
NumberGuessingGame.main(null);
-image: images/Iteration-score.png