Cmputer not following rules - java

I'm trying to come up with a reverse guessing game. Computer to guess my selected number with a range of 1-100. I do have the binary search algorithm, but when I tell the computer it's first guess is Too High, it will give me another High guess instead of going lower.
import java.util.Random;
import java.util.Scanner;
public class ComputersGuessGame {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Random value = new Random();
int computerGuess;
int highValue = 100;
int lowValue = 1;
String myAnswer;
do {
computerGuess = value.nextInt(highValue - lowValue +1)/2;
/*
*Above line should use the binary algorithm so the computer can
*make guesses and not just guess my number by going one number at a time
*/
System.out.println("I'm guessing that your number is " + computerGuess);
myAnswer = in.nextLine();
if (myAnswer.equals("tl")){
highValue = computerGuess + 1;//Too Low Answer
}
else if (myAnswer.equals ("th")){
lowValue = computerGuess - 1;//To High Answer
}
} while (!myAnswer.equals("y")); //Answer is correct
in.close();
System.out.println("Thank you, Good Game.");
}
}//Comptuer keeps making random guesses, but if I say too high, it will guess another high number instead of going low.

I think your logic to guess the next number was wrong. You should have interchange the setting the lower & high value,and change the logic to generate next guess.
here is the working solution of your problem
import java.util.Random;
import java.util.Scanner;
public class Guess {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Random value = new Random();
int computerGuess;
int highValue = 100;
int lowValue = 1;
String myAnswer;
do {
computerGuess = value.nextInt(highValue - lowValue)+lowValue;
System.out.println("I'm guessing that your number is " + computerGuess);
myAnswer = in.nextLine();
if (myAnswer.equals("tl")){
lowValue = computerGuess + 1;
} else if (myAnswer.equals ("th")){
highValue = computerGuess - 1;
}
} while (!myAnswer.equals("y"));
in.close();
System.out.println("Thank you, Good Game.");
}
}

you should try to approximate to your guess. you should try nested intervals. your working with class random, of course your computer could guess another high number again, when only lowering the range by one.
you should work with at least 2 new variables, rangeLow and rangeHigh. when to high, your new rangeHigh is your last guess. when to low, your new rangeLow is your last guess.
computerGuess = value.nextInt(rangeLow,rangeHigh);

Related

"Guess My Number" game with only allow 3 guesses from user

I've created many different types of method in my coding as my task requires to, so I faced some problems that I'm trying to incorporate loops that allow only 3 guesses from the user. After each round, the user has the option of whether to continue playing or to stop. How should I implement that? Also, any mistakes in my coding? Thank you in advanced!
import java.util.Random;
import java.util.Scanner;
public class GuessmyGame{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
Random random = new Random();
int number = random.nextInt(100)+1;
printInstruction();
int guess = in.nextInt();
guessNum(number, guess);
numberOfTries(guessNum);
}
public static void printInstruction(){
System.out.println(" I am thinking of a number between 1 and 100.");
System.out.println(" Can you guess what it is? ");
System.out.println(" Type a number : ");
}
public static void guessNum(int number, int guess){
if (number == guess){
System.out.println("Congratulations! You got it right.");
}
else if(number > guess){
System.out.println("Your guess is too low.");
Scanner in = new Scanner(System.in);
guess = in.nextInt();
System.out.println("Your guess is: "+guess);
guessNum(number, guess);
}
else{
System.out.println( "Your guess is too high.");
Scanner in = new Scanner(System.in);
guess = in.nextInt();
System.out.println("Your guess is: "+guess);
guessNum(number, guess);
}
}
public static void numberOfTries(int guessNum){
Random random = new Random();
int number = random.nextInt(100)+1;
for(int i = 0; i < 3; i++){
System.out.println("Out of guesses!");
System.out.println("The number was " + number);
}
}
}
Use a while loop and add a boolean condition.. let's call it canContinue. You'll also need to keep track of how many times the user has attempted to guess, let's say it's called attemptCount as well as the correctness of the user's latest guess (correctGuess).
When attemptCount is 3 or correctGuess is true, prompt the user if they want to continue. If their answer suggests they don't want to continue, set canContinue to false, which causes the exit the loop and complete. Otherwise, reset attemptCount (to 0 presumably to allow another 3 attempts). The code that follows highlights the requested logic. since it's clear the code provided in the question has many bugs.
var promptToRetry = false;
while (canContinue) {
if (correctGuess) {
// Let user know their guess was correct
promptToRetry = true;
}
if (attemptCount > 2) {
// Let user know they didn't get the right number
promptToRetry = true;
}
if (promptToRetry) {
boolean wantsToTryAgain = PromptUserToTryAgain(); //Code returning bool which prompts user if they want to try again (need to implement)
if (wantsToTryAgain) {
attemptCount = 0; //Resets attempt counter
correctGuess = false; //Resets the guess
promptToRetry = false;
} else {
canContinue = false; //Causes loop to exit
}
}
...
}
}

Optimizing my guessing algorithm for number guesser

I'm a relatively new coder learning Java, and my CompSci teacher assigned us something called a number guesser game, where you have to guess a random number. However, in assignment was a section on extra credit, where the user thinks of a number, and the computer has to guess what the number is in as few tries as possible.
Right now, my code for doing so looks something like this:
public static void gamone() {
System.out.println("Think of a number between 1 and anything- I'll try and guess it.");
System.out.println("What is the end of the range?");
double range = s.nextDouble();
int guess, count=0, which = 0;
double base = 0;
String response;
guess = (int) (range / 2.0);
while (count < 15) {
count++;
System.out.println("Is the number " + guess + "?");
response = s.nextLine();
response = response.toLowerCase();
if (response.contains("yes")) {
System.out.println("I'm just that good, huh?");
break;
}
else if (response.contains("no")){
System.out.println("Was is higher or lower?");
response = s.nextLine();
response = response.toLowerCase();
if (response.contains("h")) {
base = guess;
guess = (int) ((range - guess) / 2.0) + guess;
}else if (response.contains("l")) {
range = guess;
guess = guess - (int)((guess - base) / 2.0);
}
}
}
System.out.println(count);
}
I Understand the best way mathematically is to simply do what I did- to divide the difference by 2 and add or subtract that. However, is there a way I could use things like random numbers to actually make it better at guessing numbers?

Writing program to help elementary students learn multiplication

Write a program that will help an elementary school student learn multiplication. Use a SecureRandom object to produce two positive one-digit integers (you will need to look up how to do this). The program should then prompt the user with a question, such as
How much is 6 times 7? The student then inputs the answer. Next, the program checks the student’s answer. If it’s correct, display the message "Very good!" and ask another multiplication question. If the answer is wrong, display the message "No. Please try again.>again." and let the student try the same question repeatedly until the student finally gets it right.
A separate method should be used to generate each new question. This method should be called once when the application begins execution and each time the user answers the question correctly.
My question is do you have to make an if else statement == my public static mathQuestion and then have it output? I am lost on what to do after making the SecureRandom. I'm still new to Java.
I've tried doing an if-else statements after missing the question more than once but it has be done in a method.
import java.security.SecureRandom;
import java.util.;
public class h_p1 {
static SecureRandom rand = new SecureRandom();
static Scanner sc = new Scanner (System.in);
public static int mathQuestion() {
int n1 = rand.nextint(9) + 1;
int n2 = rand.nextint(9) + 1;
System.out.print("What is" + n1 + "x" + n2"?");
return r1 * r2;
}
}
}
You need to do the following:
Prompt for the answer
Check the answer by using an if statement.
If the answer is incorrect, prompt again.
If it correct, generate another question.
You will need to use loops in this situation. It could take on
different designs but you would need one for the reprompting and one for
the new question.
Imo, the best way to do the reprompting is to use a while statement with a settable boolean value. If they get the answer correct, set the boolean to false
otherwise, keep prompting while true. You could also use a for loop if you want to limit the number of guesses.
public class Quiz {
public static void main(String[] args) {
generateRandomNumbers();
}
public static void generateRandomNumbers() {
SecureRandom rand = new SecureRandom();
Scanner sc = new Scanner (System.in);
int n1 = rand.nextInt(9) + 1;
int n2 = rand.nextInt(9) + 1;
generateQuestion(n1,n2);
}
public static void generateQuestion(int n1, int n2) {
Scanner sc = new Scanner (System.in);
System.out.print("What is " + n1 + " x " + n2+ " ?");
int typedAnswer = sc.nextInt();
if(typedAnswer == (n1*n2)) {
System.out.println("Correct Answer");
generateRandomNumbers();
}else {
System.out.println("Wrong Answer");
generateQuestion(n1,n2);
}
}
}
The simplest answer to this question that I could have thought for:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
do {
SecureRandom secureRandom = new SecureRandom();
int numbOne = secureRandom.nextInt(9) + 1;
int numbTwo = secureRandom.nextInt(9) + 1;
int prod = numbOne * numbTwo;
int response;
do {
System.out.println(MessageFormat.format("What is the product of {0} and {1}", numbOne, numbTwo));
response = scanner.nextInt();
if (response != prod) {
System.out.println("Incorrect answer! Try again");
}
} while (response != prod);
System.out.println("Correct answer");
System.out.println("Do you want to practice with another question (Y/N)?");
} while (scanner.next().equalsIgnoreCase("Y"));
}
It uses 2 do-while loops. The outer loop controls the number of times a question should be asked depending on user's choice and the inner loop checks the correctness of the answer given by the user.

How to recurse back to start?

I'm a noob programmer, but I've been stuck on this one bit of code. How do you recurse back to start? I've tried several different methods but they all either take a ridiculous amount of code or don't work properly. I've been trying to implement this "simple" piece of code in all of my programming assignments, but it hasn't been working out. Thanks!
p.s. I've already finished the assignment. I'm just trying to make it more "complete".
public class OddProduct {
public static void main(String[] args) {
//Inputs from user
System.out.println("Enter an odd number");
Scanner input_odd = new Scanner(System.in);
int odd = input_odd.nextInt();
int oddproduct = 1;
//Multiplies all odd integers
for (int counter = 1; counter <= odd; counter = counter + 2){
oddproduct = oddproduct * counter;
}//end of for- loop
System.out.printf("\nThe product of all the odd integers up to %d is %d\n",
odd, oddproduct);
/* MY NOTES FOR RECURSE
if (odd%2 == 1){ proceed normally}
else if (odd%2 != 1) { HOW TO LOOP BACK???}
else { println = "Application closed"}
*/
}//end of main method
}//end of OddProduct class
Based upon your Notes I think this is what you require
Scanner input_odd = new Scanner(System.in);
int odd = 0;
while (odd % 2 != 1) { // fails first time && if user enters even number
System.out.println("Enter an odd number");
odd = input_odd.nextInt();
}

Multiplication Tutor Java Program

I am working on writing a program that follows these instructions:
Your little sister asks you to help her with her multiplication, and you decide to write a Java program that tests her skills. The program will let her input a starting number, such as 5. It will generate ten multiplication problems ranging from 5×1 to 5×10. For each problem she will be prompted to enter the correct answer. The program should check her answer and should not let her advance to the next question until the correct answer is given to the current question.
After testing ten multiplication problems, your program should ask whether she would like to try another starting number. If yes, your program should generate another corresponding ten multiplication problems. This procedure should repeat until she indicates no.
I have the code correct to ask for the multiplication part, but I can't quite figure out how to get the program to ask if the user wants to continue.
The following code has the program run through once:
package hw5;
import java.util.Scanner;
public class HW5 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter number you would like to attempt: ");
int start = input.nextInt();
int mult;
for (mult = 1; mult <= 10; mult++) {
int num = start * mult;
System.out.print(start + " x " + mult + " = ");
int ans = input.nextInt();
while (ans != num) {
System.out.print("Wrong answer, try again: ");
int ans2 = input.nextInt();
if (ans2 == num) {
break;
}
}
//System.out.print("Would you like to do another problem? ");
}
}
}
When I uncomment out line 21 the program returns:
Enter number you would like to attempt: 1
1 x 1 = 1
Would you like to do another problem? 1 x 2 = 2
Would you like to do another problem? 1 x 3 =
etc...
If I take the code from line 21 and put it outside of the for loop the program runs the for loop once and then jumps straight to the question.
How do I go about fixing this and successfully completing the instructions?
Here's how I'd do it:
package hw5;
import java.util.Scanner;
public class HW5 {
public static void main(String[] args)
{
boolean wantsToContinue = true;
while(wantsToContinue)
{
wantsToContinue = mathProblem();
}
}
public static boolean mathProblem()
{
Scanner input = new Scanner(System.in);
System.out.print("Enter number you would like to attempt: ");
int start = input.nextInt();
int mult;
for (mult = 1; mult <= 10; mult++) {
int num = start * mult;
System.out.print(start + " x " + mult + " = ");
int ans = input.nextInt();
while (ans != num) {
System.out.print("Wrong answer, try again: ");
int ans2 = input.nextInt();
if (ans2 == num) {
break;
}
}
//System.out.print("Would you like to do another problem? ");
}
boolean wantsToContinue;
//Ask if the user would like to do another problem here, set "wantsToContinue" accordingly
return wantsToContinue;
}
}

Categories