This question already has answers here:
Examples of Recursive functions [closed]
(22 answers)
Closed 5 years ago.
I am a student currently using java and I am having a hard time programming a high and low guessing game. I cannot use looping or "while" code. Any thoughts? This is what I have as of now:
public class FinalProject1
{
public static void main(String [] args)
{
System.out.println("Number Guessing Game 1-1000\nGuess a number");
guess();
}
public static int random()
{
int x = (int)(1000*Math.random() + 1);
return x;
}
public static void guess()
{
int num = random();
int tries = 0;
Scanner keyboard = new Scanner(System.in);
String inputString = keyboard.nextLine();
int input = Integer.parseInt(inputString);
if (input > num)
{
System.out.println("Guess a higher number");
inputString = keyboard.nextLine();
}
else if (input < num)
{
System.out.println("Guess a lower number");
inputString = keyboard.nextLine();
}
else if (num == input)
{
System.out.println("You Win");
}
}
}
A few things..
Your > & < checks for higher and lower are backwards
You need to be using recursion in order to produce your intended behavior without any loops.
public static void main(String [] args)
{
System.out.println("Number Guessing Game 1-1000\nGuess a number");
int num = random();
Scanner keyboard = new Scanner(System.in);
guess(keyboard, num);
}
public static int random()
{
int x = (int)(1000*Math.random() + 1);
return x;
}
public static void guess(Scanner keyboard, int goal)
{
String inputString = keyboard.nextLine();
int input = Integer.parseInt(inputString);
if (input < goal)
{
System.out.println("Guess a higher number");
guess(keyboard, goal);
}
else if (input > goal)
{
System.out.println("Guess a lower number");
guess(keyboard, goal);
}
else if (input == goal)
{
System.out.println("You Win");
}
}
Basically what's happening is that we are getting their response and checking if it's > or < the result, telling them, and the immediately calling the guess() method again in order to repeat this process until they get it right.
Wrapping your head around recursion can be fairly difficult in the beginning, just keep practicing
First, your logic is flawed. If input > num then user guessed too high, and needs to guess a lower number.
Others have suggested to use recursion, and that's the common solution for your problem, and is likely what you need to do, since you likely have just learned about recursion.
But, since I like to be contrary, I'd do it by starting a new thread, like this:
public class FinalProject1 implements Runnable {
private Scanner keyboard = new Scanner(System.in);
private int num = random();
public static void main(String[] args) {
System.out.println("Number Guessing Game 1-1000\nGuess a number");
new Thread(new FinalProject1()).start();
}
public static int random() {
return (int) (1000 * Math.random() + 1);
}
#Override
public void run() {
String inputString = this.keyboard.nextLine();
int input = Integer.parseInt(inputString);
if (input > this.num) {
System.out.println("Guess a lower number");
new Thread(this).start();
} else if (input < this.num) {
System.out.println("Guess a higher number");
new Thread(this).start();
} else if (this.num == input) {
System.out.println("You Win");
}
}
}
Related
I'm new to programming and I'm making a guessing game where the program randomly generates a number between 1 and 10, the user then is asked to guess what the number is, the user should be able to keep guessing until he guesses correctly and the system asks them if they want to play again,
In my code I've printed the number that the system has randomly generated so that it is quicker to complete the game whilst testing. When I try and execute the program and enter the number that the system has generated the message that they are correct and asking if they want to play again does not come up.
Any help would be greatly appreciated!
Thank you in advance,
(Also, anything wrong with this question just tell me, it's my first time asking on here)
Here is my code,
import java.util.Scanner;
import java.util.Random;
public class GuessingGame1 {
public static int randomizer() {
Random rand = new Random();
int num = rand.nextInt(10)+1;
System.out.println(num);
int count = 0;
return num;
}
public static int userInput() {
System.out.println("I've thought of a number between 1 and 10");
System.out.println("Enter your guess...");
Scanner scan = new Scanner(System.in);
int guess = scan.nextInt();
return guess;
}
public static String compare() {
int count = 0;
String result = null;
if (userInput() == randomizer()) {
System.out.println("You guessed it - I was thinking of " + randomizer());
count++;
result = "It took you " + count + " guesses.";
return result;
}
else if (userInput() > randomizer()) {
result = "Lower!";
count++;
return result;
}
else if (userInput() < randomizer()) {
result = "Higher";
count++;
}
return result;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Scanner scanLine = new Scanner(System.in);
String playAgain = "";
do {
randomizer();
do {
userInput();
compare
} while (userInput() != randomizer());
System.out.println("Play again? Yes/No");
playAgain = scanLine.nextLine();
} while (playAgain.equalsIgnoreCase("yes") || playAgain.equalsIgnoreCase("y"));
}
}
The problem is that you call twice to Randomizer!
call randomizer once as parameter to compare and return boolean from compare for a match.
You must change your methods something like this
public static String compare(int a,int b) {
int count = 0;
String result = null;
if (a == b) {
System.out.println("You guessed it - I was thinking of " + b);
count++;
result = "It took you " + count + " guesses.";
return result;
}
else if (a > b) {
result = "Lower!";
count++;
return result;
}
else if (a < b) {
result = "Higher";
count++;
}
return result;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Scanner scanLine = new Scanner(System.in);
String playAgain = "";
int a;
int b;
do {
do {
a=userInput();
b= randomizer();
System.out.println(compare(a,b));
} while (a != b);
System.out.println("Play again? Yes/No");
playAgain = scanLine.nextLine();
} while (playAgain.equalsIgnoreCase("yes") || playAgain.equalsIgnoreCase("y"));
}
}
you have left the () in compare and the count will always be zero as it is been initialized when the compare function is called.
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!
I know this question has been asked several times already. Feel free to mark it as a duplicate. Anyway, I'd rather ask the community since I am still uncertain.
I should convert this while loop in a do-while loop.
Any thoughts?
public class DoWhile {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int sum = 0;
System.out.println("Enter an integer " + "(the input ends if it is 0)");
int number = input.nextInt();
while (number != 0) {
sum += number;
System.out.println("Enter an integer " + "(the input ends if it is 0)");
number = input.nextInt();
}
}
}
You cant just simple convert any while loop to do while loop , the main difference between them is in do while loop you have an iteration that will happen regardless of the condition.
public class DoWhile {
public static void main(String[] args) {
int number=0;
Scanner input = new Scanner(System.in); int sum = 0;
do{ System.out.println("Enter an integer " +"(the input ends if it is 0)");
number = input.nextInt();
sum += number;
}while (number != 0) ;
}
}
public class DoWhile {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int sum = 0;
int number = 0;
do {
System.out.println("Enter an integer " +
"(the input ends if it is 0)");
number = input.nextInt();
sum += number;
} while(number != 0)
}
}
You have to tell the program to continue doing something in the "do" block. In your own case you have to tell the program to keep doing this"
System.out.println("Enter an integer " + "(the input ends if it is 0)"); number = input.nextInt();
sum += number;". Then in the "while" block you will have to provide the terminating statement, in your own case "number != 0"
public class DoWhile {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int sum = 0;
int number;
do {
System.out.println("Enter an integer " + "(the input ends if it is 0)");
number = input.nextInt();
sum += number;
} while (number != 0);
}
}
public class DoWhile {
public static void main(String[] args) {
Scanner input = new Scanner(System.in); int sum = 0;
System.out.println("Enter an integer " + "(the input ends if it is 0)");
int number = input.nextInt();
//You need this if statement to check if the 1st input is 0
if(number != 0)
{
do
{
sum+=number;
System.out.println("Enter an integer " + "(the input ends if it is 0)");
number = input.nextInt();
}while(number != 0);
}
}
}
classInfoClass
{
public void setinfo()
{
int userage;
do
{ Console.Write("Please enter your age: ");
} while (!int.TryParse(Console.ReadLine(),out userage));
I am trying to write a method that calculates the sum of odd integers between 1 and a given positive integer n, without using anything else than if statements (sheesh!). It worked out just fine until I decided to also create a method that would ask recursively for the number until it was positive and use it to get n.
Now my program outputs the correct results until I enter a negative number. It then asks for a postive one until I enter one and it outputs 0, the value I initialised the variable val with.
I'm not sure where the logic error is. Could you please take a look? I'm sure it's something obvious, but I guess I have just reached the end of my wits today. Thanks!
package oddsum;
import java.util.Scanner;
public class Oddsum {
public static int oddSum(int n){
int val=0;
if(n>1){
if(n%2==0){
val=n+oddSum(n-1);
}else{
val=oddSum(n-1);
}
}
return val;
}
public static int request(int n){
Scanner in= new Scanner(System.in);
System.out.println("Give me a positive integer: ");
n=in.nextInt();
if (n<0){
System.out.println("I said positive! ");
request(n);
}
return n;
}
public static void main(String[] args) {
int val=0;
int n=request(val);
System.out.println(oddSum(n));
}
}
You should remove input parameter from your request() method. Because your negative input is carried out through the recursive call.
public class Oddsum {
public static int oddSum(int n) {
int val = 0;
if (n > 1) {
if (n % 2 == 0) {
val = n + oddSum(n - 1);
} else {
val = oddSum(n - 1);
}
}
return val;
}
public static int request() {
Scanner in = new Scanner(System.in);
System.out.println("Give me a positive integer: ");
int n = in.nextInt();
if (n < 0) {
System.out.println("I said positive! ");
return request();
}
return n;
}
public static void main(String[] args) {
int n = request();
System.out.println(oddSum(n));
}
}
Output;
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);
}