i'm learning Java with the book think Java : how to think like a computer scientist ? and there is no exercise answers in the book, usually i end up finding similar exercices on different websites but not for this one because i have precise instructions. Can you please tell me if it's correct.
I think the problem is solved, the job is done, but is there an easier way to do it ?
Thanks a lot
Exercise 5-7.
Now that we have conditional statements, we can get back to the “Guess My Number” game from Exercise 3-4.
You should already have a program that chooses a random number, prompts the user to guess it, and displays the difference between the guess and the chosen number.
Adding a small amount of code at a time, and testing as you go, modify the program so it tells the user whether the guess is too high or too low, and then prompts the user for another guess.
The program should continue until the user gets it right. Hint: Use two methods,
and make one of them recursive.
import java.util.Random;
import java.util.Scanner;
public class GuessStarter {
public static void Lower(int number,int number2) {
Scanner in = new Scanner(System.in);
System.out.print("Too Low , try again ");
number2 = in.nextInt();
if (number2==number) {
System.out.println("You're right");}
else if (number2>number)
Higher(number,number2);
else
Lower(number,number2); }
public static void Higher(int number,int number2) {
Scanner in = new Scanner(System.in);
System.out.print("Too high , try again ");
number2 = in.nextInt();
if (number2==number) {
System.out.println("You're right");}
else if (number2>number)
Higher(number,number2);
else
Lower(number,number2); }
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Random random = new Random();
int number = random.nextInt(100) + 1;
int number2;
System.out.print("Type a number: ");
number2 = in.nextInt();
if (number2==number) {
System.out.println("You're right");}
else if (number2>number)
Higher(number,number2);
else
Lower(number,number2);}
}
Don't know if it'll be useful now or not, but, as I was solving the same solution, thought of letting it know if someone finds it useful:
import java.util.Random;
import java.util.Scanner;
/**
* Created by RajU on 27-Jun-17.
*/
public class GuessNumber2 {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
message("I'm thinking of a number between 1 and 10 (including both).\n" +
"Can you guess what it is?\n" +
"Type a number: ");
int userNumber = input.nextInt();
tryAgain(userNumber, calculateRandom(10));
}
public static int calculateRandom(int n) {
Random random = new Random();
return random.nextInt(n) + 1;
}
public static void tryAgain(int userNumber, int generateRandom) {
if (userNumber == generateRandom) {
message("You're absolutely right!");
} else {
if (userNumber > generateRandom) {
message("Think of a lesser number: ");
} else {
message("Think of a greater number: ");
}
userNumber = input.nextInt();
tryAgain(userNumber, generateRandom);
}
}
public static void message(String m) {
System.out.print(m);
}
}
I just completed this exercise. It's pretty interesting to see some different approaches! Here's my take on it:
import java.util.Random;
import java.util.Scanner;
public class GuessGameLevelUp {
/*
* A guessing game where you try to guess a random number between and including 1 and 100.
* This version allows you to continue guessing until you get the right answer.
* When you're off, a hint will let yet know whether your most recent guess was too high or low.
*/
public static void main (String [] args) {
//Generates a random number for the game
Random random = new Random();
int answer = random.nextInt(100) +1;
//Introduces the game and gives a prompt
System.out.println("I'm thinking of a number between and including "
+ "1 and 100, can you guess which?");
System.out.print("Take a guess: ");
//Enables guess value input and parrots guess
Scanner in = new Scanner(System.in);
int guess;
guess = in.nextInt();
System.out.println("Your guess is: "+guess);
//Stacks a new class to determine the outcome of the game
tooHighTooLow(answer, guess);
}
public static void tooHighTooLow(int a, int g) {
//Triggers and parrots guess if correct
if (a==g) {
System.out.print("Correct! The number I was thinking of was: "+g);
//Triggers "Too Low" prompt and uses recursive to offer another attempt
} else if (a>g) {
System.out.print("Too Low! Try again: ");
Scanner in = new Scanner(System.in);
g = in.nextInt();
System.out.println("Your guess is: "+g); //Parrots guess
tooHighTooLow(a, g);
//Triggers "Too High" prompt and uses recursive to offer another attempt
}else
System.out.print("Too high! Try again: ");
Scanner in = new Scanner(System.in);
g = in.nextInt();
System.out.println("Your guess is: "+g); //Parrots guess
tooHighTooLow(a, g);
}
}
I got stuck on this one too, but your code helped me in arriving at a solution. Here's what I came up with:
import java.util.Random;
import java.util.Scanner;
public class Ch5Ex7 {
public static void compareNumbers(int userNumber,int randomNumber) {
if(userNumber == randomNumber) {
System.out.println("You got it!");
} else if ( userNumber > randomNumber ) {
System.out.println("Too high. Guess again: ");
Scanner in = new Scanner(System.in);
userNumber = in.nextInt();
compareNumbers(userNumber, randomNumber);
} else {
System.out.print("Too low. Guess again: ");
Scanner in = new Scanner(System.in);
userNumber = in.nextInt();
compareNumbers(userNumber,randomNumber);
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Random random = new Random();
int randomNumber = random.nextInt(100) + 1;
int userNumber;
System.out.print("Type a number: ");
userNumber = in.nextInt();
compareNumbers(userNumber, randomNumber);
}
}
Thanks for pointing me in the right direction!
Related
this is guess number programme using constructor but the issue which I am facing
is not able to express user input in loop.I tried to look for it but not good explanation.
import java.util.Scanner;
import java.lang.Math;
class guessnumber{
public int getRandomNumber(int min, int max) {
return (int) ((Math.random() * (max - min)) + min);
}
public String userinput(int repeats,int rand){
String e;
e="that's it";
if(repeats<rand){
String z="choose higher number";
System.out.println(z);
}
else if (repeats>rand){
String z="choose lower number";
System.out.println(z);
}
return e;
}
public String iscorrect(){
String correct="correct number";
return correct;
}
}
public class guessthenumber {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
guessnumber gun = new guessnumber();
System.out.println("enter number ");
int number = sc.nextInt();
System.out.println("enter max and min number");
int min = sc.nextInt();
int max = sc.nextInt();
int o=gun.getRandomNumber(min,max);
System.out.println(o);
if (number < o || number > o) {
System.out.println(gun.userinput(number, o));}
else if(number==o){
String correct= gun.iscorrect();
System.out.println(correct);
}
}
}
I want to user to keep entering data till correct number is hit
Here's a solution that behaves like you're describing, and how your code currently behaves:
ask for a few numbers up front (minimum, maximum)
determine a random "target" number for the user to guess
ask the user to guess – if they're correct, show a message; if they're incorrect, ask for another guess
repeat until their guess is correct
A few things I did:
introduce a "getNumber()" helper that will make sure the numbers make sense – put some guardrails around what a user can enter to minimize unexpected results if user enters unexpected input
use a "while" loop, go forever – while (true)
if their guess matches the target, use break to stop the loop
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int minimum = getNumber(scanner, 0, "minimum");
int maximum = getNumber(scanner, minimum + 1, "maximum");
int target = (int) ((Math.random() * (maximum - minimum)) + minimum);
while (true) {
System.out.print("enter a guess: ");
int guess = scanner.nextInt();
if (guess == target) {
System.out.println("correct guess! the number was " + target);
break;
} else {
System.out.print("nope, please try again.. ");
}
}
}
static int getNumber(Scanner scanner, int minimumAllowed, String numberType) {
while (true) {
System.out.print("enter " + numberType + " number: ");
int minimum = scanner.nextInt();
if (minimum >= minimumAllowed) {
return minimum;
} else {
System.out.println("too small, must be at least " + minimumAllowed);
}
}
}
Here's a sample run:
enter minimum number: 1
enter maximum number: -3
too small, must be at least 2
enter maximum number: 5
enter a guess: 1
nope, please try again.. enter a guess: 2
nope, please try again.. enter a guess: 3
nope, please try again.. enter a guess: 4
correct guess! the number was 4
You can use while and break statements
Im struggling with that code.
how can I use string with yes/no on that question: n1>n2, n1<n2.
the operators also need to change.
import java.util.Scanner;
import java.util.Random;
public class s {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
Random r = new Random();
int n1 = r.nextInt(10) + 1;
int n2 = r.nextInt(10) + 1;
int max = Math.max(n1, n2);
System.out.println("What is higher: "+n1+" or "+n2+" ");
int result = s.nextInt();
if(result==max)
System.out.println("Well done");
else
System.out.println("Wrong answer");
}
}
I tried a way to not use a lot of IF’S by splitting the two possible cases and not having many repeated coding lines.
By avoiding this situation, I started creating: random numbers, the random operator “>” or “<” and a boolean variable which value depends on the answer of the user.
Then I defined a variable called “reality” that will provide the correct answer, referring to which number is bigger or smaller than the other.
Finally, the program verifies if the answer of the user is the same to the reality printing the expected answer.
public static void main(String[] args) {
int bol_op= (int) Math.random()>0.5?1:0;
String operator= bol_op==1?">":"<";
int num1=(int) (Math.random()*100+1);
int num2=(int) (Math.random()*222+1);
String str_num1=num1+"";
String str_num2=num2+"";
Scanner sc= new Scanner(System.in);
System.out.println("********Logic Program**********");
System.out.println("Question: "+str_num1+operator+str_num2);
System.out.print("Answer (yes/no): ");
String answer =sc.nextLine().toLowerCase();
boolean value=false;
if(answer.equals("yes")){
value=true;
}
boolean reality=num1>num2?true:false;
if(bol_op==0){
reality=num1<num2?true:false;
}
if(reality==value){
System.out.println("Well done");
}
else{
System.out.println("Wrong answer");
}
}
so this my first time coding and i need a lot of help trying to figure out to get the total amount of guesses and the total amount games played, i dont even know where to start. I can get the code to tell me how many guesses it took to get to the number in one game but not the overall result. Any tips or help?
thank you
import java.util.Scanner;
import java.util.Random;
public class treehouseproject {
//Instruction on how to play the game
public static void instruction() {
System.out.println("this is a guessing game");
System.out.println("you will guess the number");
System.out.println("that i am thinking of");
System.out.println("unitl you guess the correct number");
System.out.println("the number ranges from 0 to 100");
}
//playing a single game
public static void playgame() {
int guessNumber = 0;
int numberGuesses = 0;
int plays = 0;
int max = 100;
int min = 0;
Random randomNum = new Random();
int givenNumber = min + randomNum.nextInt(max);
Scanner scan = new Scanner (System.in);
while(guessNumber != givenNumber){
numberGuesses++;
System.out.println("Guess: " + numberGuesses);
guessNumber = scan.nextInt();
if (guessNumber == givenNumber) {
System.out.println("correct");
System.out.println("you go it right in " + numberGuesses + " guesses");
}
if (guessNumber < givenNumber) {
System.out.println("higher");
}
if (guessNumber > givenNumber){
System.out.println("lower");
}
}
}
//playing muliple games and reporting all end stats
public static void main(String[] args) {
String Answer = "";
instruction();
playgame();
Scanner console = new Scanner(System.in);
System.out.println("do you want to play again?");
Answer = console.nextLine();
boolean keep_playing = true;
while (Answer.equalsIgnoreCase("yes")){
playgame();
System.out.println("do you want to play again?");
Answer = console.nextLine();
}
}
//prints out the stats of the game
public static void results(int plays, int numberGuesses) {
System.out.println("Overall results");
System.out.println("Total amount of guesses = " + numberGuesses);
System.out.println("Total amount of games = " + plays);
}
}
the problem you are encountering actually has a pretty simple solution.
So if you define a variable it as a certain "lifespan" this means that is effectively dies at some point.
Every variable is only "alive" within the parents of its parent.
Example:
public static void main(string args[]){
String s1 = "";
private static void doSomething(){
String s2 = s1;
}
}
The variable s1 is "alive" until the parenthesizes of its parent (main) close, so its also alive within the function and fully usable.
s2 on the other hand is only alive within "doSomething", so it cannot be referenced after its bracket closes.
So moving the initialization of variables to a more "global" level is often very usefull.
You need to move the initialization of the these variables outside of playGame() and to the global level.
numberGuesses
plays
I'm trying to make this code print out the number of games played (gameNum). Instead, it always sets gameNum to 2, and prints out the last println the number of times that the game was played. I feel like I made a dumb mistake here, but I am having trouble finding it. Could you please give me a hint instead of the answer? I'd like to figure this out on my own. If not, then feel free to go ahead and write the answer.
Thanks!
import java.util.*;
public class Testing_gameNum {
public static final int amt = 1;
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
guessCounter(console);
}
public static int game(Scanner console) {
Random rand = new Random();
int guess = 0;
int guessNum = 0;
System.out.printf("I'm thinking of a number...", amt);
System.out.println();
int num = 1;
do {
System.out.println("Your guess? ");
guess = console.nextInt();
guessNum += guessNum;
} while (guess != num);
return guessNum;
}
public static void guessCounter(Scanner console) {
int gameNum = 1;
int guessNum = game(console);
if (guessNum == 1){
System.out.printf("You won in %d guesses!", guessNum);
System.out.println();
}
gameNum = gameNum + 1;
System.out.println("Do you want to play again?");
String play = console.next();
if (play.equals("y")) {
guessCounter(console);
}
System.out.println("Number of games: " + gameNum);
}
}
Try something like this:
public class Testing_gameNum
{
public static final int amt = 1;
public static void main(String[] args)
{
Scanner console = new Scanner(System.in);
guessCounter(console);
}
public static int game(Scanner console)
{
Random rand = new Random();
int guess = 0;
int guessNum = 0;
System.out.printf("I'm thinking of a number...", amt);
System.out.println();
int num = 1;
do
{
System.out.println("Your guess? ");
guess = console.nextInt();
guessNum += amt;
}
while (guess != num);
return guessNum;
}
public static void guessCounter(Scanner console)
{
int gameNum = 1;
do
{
int guessNum = game(console);
if (guessNum == 1)
{
System.out.printf("You won in %d guesses!", guessNum);
System.out.println();
}
gameNum = gameNum + 1;
System.out.println("Do you want to play again?");
String play = console.next();
}
while (play.equals("y"))
System.out.println("Number of games: " + gameNum);
}
}
Check for every place gameNum is used. I found it i.e. in the method guessCounter(Scanner console) - and only there.
So every time you call this method, the value of gameNum is initialized to 1. After the game is won, you increment it by 1 and later on print it, hence the 2 in the output.
Move int gameNum = 1; out of the method guessCounter(Scanner console). This should help.
Aside of this please review also the code block
if (play.equals("y")) {
guessCounter(console);
}
Imagine a player goes on and on, always selecting "y". With every game round, you create another level of recursion. This "do you want to play again" could be implemented by a do-while loop, this will avoid the recursion.
You've defined guessCounter to be a recursive method, but that's probably not what you want for several reasons. First, each time you call guessCounter, you're creating a new gameNum and setting it to 1. You play the game and increment it to 2, but then recurse and never touch that variable again, which is the cause of your bug. Additionally, (although this is unlikely to happen in usual play), you could overflow your stack if you play the game enough times. Each time you play the game, the computer needs to remember the point in code that it needs to return to when it completes that call of guessCounter. Eventually you will run out of memory to store those pointers. Recursion is good for certain problems, but it's better to use loops most of the time.
How about using a loop rather than recursion.
I solved my question! Here's the code (explanation below):
public class Testing_gameNum {
public static final int amt = 1;
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
guessCounter(console);
}
public static int game(Scanner console) {
Random rand = new Random();
int guess = 0;
int guessNum = 0;
System.out.printf("I'm thinking of a number...", amt);
System.out.println();
int num = 1;
do {
System.out.println("Your guess? ");
guess = console.nextInt();
guessNum ++;
} while (guess != num);
return guessNum;
}
public static void guessCounter(Scanner console) {
int gameNum = 0;
String play = "y";
do {
int guessNum = game(console);
gameNum += 1;
if (guessNum == 1) {
System.out.printf("You won in %d guesses!", guessNum);
System.out.println();
}
System.out.println("Do you want to play again?");
play = console.next();
} while (play.equals("y"));
System.out.println("Number of games: " + gameNum);
}
}
MY PROBLEMS: gameNum was resetting each time I called guessCounter. I needed a do/while loop; that way, I could initialize gameNum inside the method, and then loop only the section of the method that needed to be repeated. The repetitive println was linked with that same issue: it was reprinted each time I called guessCounter, as opposed to just the part of the code I wanted repeated.
Thanks for your help, everyone!
I'm a novice coder looking for some help. I had to write this program where the user guesses a number between 0 and 100 and then in response is told if it is higher or lower. Below is the code. My question is, sometimes when I put in a number, usually 99 the program terminates and I have no idea why. I have been looking at the code for 2 hours and cannot figure out what causes the program to terminate. Any help would be appreciated.
import java.util.Scanner;
import java.util.Random;
public class Proj71 {
private static int userNumber;
private static int firstguess = 1;
private static int numguess1;
private static int numguess2;
private static int totalguess;
private static Random generator = new Random();
private static Scanner reader = new Scanner(System.in);
private static int compNumber = generator.nextInt(100);
public static void main(String[] args) {
UserGuess();
UserHighGuess();
UserLowGuess();
UserEquals();
}
private static void UserGuess() {
System.out.println("What number am I thinking of between 0 and 100?: ");
userNumber = reader.nextInt();
}
private static void UserHighGuess() {
while (userNumber > compNumber) {
System.out.println("Lower! Try again: ");
userNumber = reader.nextInt();
numguess1++;
}
}
private static void UserLowGuess() {
while (userNumber < compNumber) {
System.out.println("Higher! Try again: ");
userNumber = reader.nextInt();
numguess2++;
}
}
private static void UserEquals() {
if (userNumber == compNumber) {
totalguess = numguess1 + numguess2 + firstguess;
System.out.println("You got it!");
System.out.println("Total number of guess: " + totalguess);
}
}
}
Thanks,
Jmanlikescake (sorry if this post is really bad)
The issue is with the structure of the program.
You are calling
UserGuess();
UserHighGuess();
UserLowGuess();
UserEquals();
What if the number was 50, and the user guessed 30? We'd be in the body of UserLowGuess().
Then imagine the user entered 55. The UserLowGuess() would be broken out of as the userNumber is greater than the compNumber. So then, you would be in UserEquals. But since 55 is not equal to 50, the if statement will not be entered and the program will exit.
I would recommend putting this into one while loop, not three. I haven't tested this, FYI.
This loops continuously accepting user input until a match is found.
public static void main(String[] args) {
UserGuess();
}
private static void UserGuess() {
System.out.println("What number am I thinking of between 0 and 100?: ");
userNumber = reader.nextInt();
totalguess = 1;
while (userNumber != compNumber) {
if (userNumber > compNumber) {
System.out.println("Lower! Try again: ");
} else if (userNumber < compNumber) {
System.out.println("Higher! Try again: ");
}
userNumber = reader.nextInt();
totalguess++;
}
System.out.println("You got it!");
System.out.println("Total number of guess: " + totalguess);
}