Write a program named NumberGame that has the user pick a nu
Write a program named NumberGame that has the user pick a number from 1 to 10.
Then the computer will start guessing by choosing a random number from 1 to 10, The computer will get up to 10 tries to guess the correct number, if the computer picks a number before its trys are up, then it will stop and not pick any more since it won. The computer has no memory of what its earlier picks are, so it just randomly picks a new number from 1 to 10 every time, it many times picks the same number that it already tried.
If the computer failed to pick the correct number, it loses.
The computer will print whether the user or the computer won.
You should write and use a method called computerPlay that takes an int parameter with the number the user input, and returns a boolean value indicating if the computer won. true would be the computer won.
This method will do the computer play part of printing the phrase \"Computer picks: \" and then each number as the computer picks them, and the returning from the method with a true if the computer picks the correct number by the 10 th pick and false if the computer gets the first 10 picks wrong. It prints each new pick as shown below.
Once the method returns the boolean value to main, code in main will print either \"computer wins!\" or \"you win!\"
You prompt and input from the user should all be on one line (user print for prompt). And the computerPlay method output should be on one line. (use print) the final win statement should be at the end of the line. (use println)
NOTE: This is for Java
example 1: pick a number: 10 Computer picks: 9 1 1 2 4 3 7 2 2 10 computer wins! example 2: pick a number: 1 Computer picks: 9 6 7 9 1 computer wins! example 3: pick a number: 8 Computer picks: 2 7 3 6 2 2 10 5 7 1 you win! |
Solution
NumberGame.java
import java.util.Random;
import java.util.Scanner;
public class NumberGame {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println(\"PICK A NUMBER: \");
int userChoice = input.nextInt();
boolean result = computerPlay(userChoice);
if (result)
System.out.println(\"You Win!!\");
else
System.out.println(\"Computer Wins\");
}
public static boolean computerPlay(int userChoice) {
Random r = new Random();
int Low = 1;
int High = 10;
System.out.println(\"Computer Picks: \");
for (int count = 0; count < 10; count++) {
int randomNumber = r.nextInt(High - Low) + Low + 1;
System.out.print(randomNumber + \" \");
if (randomNumber == userChoice) {
return true;
}
}
return false;
}
}