Question: What is wrong with my code import java.util.Scanner; import java.util.Random; public class Project 2 { public static void main ( String [ ] args )

What is wrong with my code
import java.util.Scanner;
import java.util.Random;
public class Project2{
public static void main(String[] args){
Scanner scnr = new Scanner(System.in);
while (true){
System.out.println("1. Guess your number");
System.out.println("2. Guess my number");
System.out.println("3. Exit");
int choice = scnr.nextInt();
if (choice ==1){
guessYourNumber();
continue;
}
if (choice ==2){
guessMyNumber();
continue;
}
if (choice ==3){
System.out.println("Goodbye");
break;
}
System.out.println("Invalid input");
}
}
public static void guessYourNumber(){
System.out.println("Think of a number from 0 to 100.");
int low =1, high =100, tries =0;
int maxTries =7;
Scanner scnr = new Scanner(System.in);
while (tries < maxTries){
int guess =(low + high)/2;
tries++;
System.out.println("CPU guesses "+ guess);
System.out.println("Type 'y' if the number is correct, 'h' if the number is higher, and 'l' if the number is lower");
String cpuGuess = scnr.nextLine().toLowerCase();
if (cpuGuess.equals("y")){
System.out.println("You lose. Game over. :(
");
return;
}
if (cpuGuess.equals("h")){
high = guess -1;
continue;
}
if (cpuGuess.equals("l")){
low = guess +1;
continue;
}
System.out.println("Invalid input");
}
System.out.println("You got me. You win! :)
");
}
public static void guessMyNumber(){
Random randGen = new Random();
int correctNum = randGen.nextInt(100)+1;
int tries =0;
final int maxTries =10;
Scanner scnr = new Scanner(System.in);
System.out.println("Try to guess the number I picked. From 1-100");
while (tries < maxTries){
System.out.print("Input your guess: ");
int userGuess = scnr.nextInt();
tries++;
if (userGuess < correctNum){
System.out.println("Lower");
continue;
}
if (userGuess > correctNum){
System.out.println("Higher");
continue;
}
System.out.println("Congratulations. That was the number. You win! :)");
return;
}
System.out.println("All attempts used. The number was "+ correctNum +". You lose. Game over. :(
");
}
}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!