Adding simple selection and iteration to our code allows us to build a variety of fun programs. For this activity, we'll apply these concepts to create a classic number guessing game.
import java.util.Scanner;
public class Program { public static void main(String[] args) { Scanner input = new Scanner(System.in); int secretNumber = (int)(Math.random() * 10) + 1; int guess = 0; int tries = 0; }}import java.util.Scanner;
public class Program { public static void main(String[] args) { Scanner input = new Scanner(System.in); int secretNumber = (int)(Math.random() * 10) + 1; int guess = 0; int tries = 0;
while (guess != secretNumber) { System.out.print("Guess the number (1-10): "); guess = input.nextInt(); tries++;
if (guess == secretNumber) { System.out.println("Correct! It took you " + tries + " tries!"); } else if (guess > secretNumber) { System.out.println("Wrong! Your guess was too high."); } else { System.out.println("Wrong! Your guess was too low."); } } }}//import java.util.Scanner;
public class Program { public static void main(String[] args) { Scanner input = new Scanner(System.in); int secretNumber = (int)(Math.random() * 10) + 1; int guess = 0; int tries = 0;
while (guess != secretNumber) { System.out.print("Guess the number (1-10): "); guess = input.nextInt(); tries++;
if (guess == secretNumber) { System.out.println("Correct! It took you " + tries + " tries!"); } else if (guess < 1 || guess > 10) { System.out.println("Your guess was out of range."); } else if (guess > secretNumber) { System.out.println("Wrong! Your guess was too high."); } else { System.out.println("Wrong! Your guess was too low."); } } }}//Your program output should something similar to the sample output below.
Guess the number (1-10): 6Wrong! Your guess was too high.Guess the number (1-10): 3Wrong! Your guess was too low.Guess the number (1-10): 5Wrong! Your guess was too high.Guess the number (1-10): 4Correct! It took you 4 tries!You may write your reflection answers as comments at the bottom of your code.
Submit your activity and reflection answers to the appropriate dropbox.