简体   繁体   中英

Beginner Java program, loops

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"); 
        }
    }   
}

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 .
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?

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;
}

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 .

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM