1

I am trying to create a simple program which creates a random number and asks the user to guess. It will then say higher or lower until the user guesses correct. The problem is, after the user guesses correctly the program will keep looping. I thought that putting the code into a separate method and then calling it in a while loop would work but unfortunately it was no avail. Could anyone suggest how I would correct this?

Below is my code.

package main;
public class NumberGuesser {


    public static void main(String[] args) {
        code mycode = new code();
        while (mycode.guess != mycode.random){
            mycode.codebit();      
        }
    }

}


package main;
import java.util.Random;
import java.util.Scanner;


public class code {


    Random rand = new Random();     
    int random = rand.nextInt(1000);
    double guess;

    public void codebit(){

        System.out.println("Guess the number"); 
        Scanner input = new Scanner(System.in);
        Double guess = input.nextDouble();
        if (guess > random){
            System.out.println("Lower");    
        }
        else if (guess < random){
            System.out.println("Higher");   
        }
        else if (guess == random){
           System.out.println("Well done"); 
        }
    }   
}
3
  • Welcome to programming anyway :) Commented Jan 30, 2014 at 17:30
  • @KevinWorkman MVC is a bit overkill for a total beginner though ;) Commented Jan 30, 2014 at 17:32
  • @Fabinout I appreciate the feedback, and while I agree with the general idea that strict MVC is too much for a novice, the tutorials introduce OOP through Processing before jumping into Java. And I posted it here because even if the OP doesn't understand everything, he'll hopefully see the basic flow of the program, which is what he's confused about here. Commented Jan 30, 2014 at 17:35

5 Answers 5

4

You are re-declaring guess within your method body, which hides your instance member. Try removing:

Double guess = input.nextDouble();

... and replacing with:

guess = input.nextDouble();

Also non-related to your issue:

  • As general coding guidelines go, class names should be CamelCase
  • You don't need to instantiate a Scanner each time. If you experiment with your code structure, you'll be able to have more efficient usage. Just a hint, try looking for the hasNext[...] methods of Scanner.
Sign up to request clarification or add additional context in comments.

1 Comment

This fixed the program perfectly. Surprised it was so simple! Thanks ever so much for your help
0
Double guess = input.nextDouble();

You're initializing a local variable which has the same name as the field here. The field, that is checked by the main class, is never modified. Also, why do you use a double and not an int for the guess?

Comments

0

I think you do not have to go into a separate method here. Just put the code you have in your code class into your main method into an infinite loop. This way, you will be able to stop the program by returning when the guess is correct:

else if (guess == random) {
    System.out.println("Well done");
    return;
}

Comments

0

your global value guess never be assigned with a value except it first assign a value (that is 0) from system as global variable.
This is caused as you declared a local variable and assigning the local variable every time instead global variable as default java properties.
Removing the declaration of local variable guess can be a solution of that problem. You can solved it other ways to like assign global with local using this.guess = guess.

Comments

0

I'm also pretty new to Java but I would keep it simple and do it like this:

package main;
import java.util.Random;
import java.util.Scanner;

public class GuessNumber {

    public static void main(String[] args) {

        Random rand = new Random(); 
        Scanner input = new Scanner(System.in);    
        int guess;
        int randomNum;
        String answer = "";

        System.out.println("~ WELCOME! ~");
        System.out.println("Can you guess the secret number?");

        do {
            System.out.print("\nPicking a number between 1-1000........ ");
            randomNum = rand.nextInt(1000)+1; //number will be between 1-1000

            System.out.println("Done!");
            System.out.print("\nGuess the number: ");

            guess = input.nextInt();

            while(guess<1 || guess>1000) {
                System.out.println("\nOut of range! Try again.");
                System.out.print("Your guess: ");
                guess = input.nextInt();
            }

            if(guess==randomNum)
                System.out.print("You were right!");

            else 
                System.out.println("\nWrong! Better luck next time.");  

            System.out.println("\nThe secret number was " + randomNum + ".");
            System.out.println("Your guess was " + guess + ".");

            System.out.print("\nPlay again (yes/no)? ");
            answer = input.next();

            if(answer.equalsIgnoreCase("no")) {
                System.out.print("\nThanks for playing!");
                input.close();
                System.exit(0);
            }

        }while(answer.equalsIgnoreCase("yes")); 
    }    
}

I don't think it's really necessary to create another class. Try it out and see what you think!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.