Home > Back-end >  Why does the Random method produce the name of the method when being printed? [Java]
Why does the Random method produce the name of the method when being printed? [Java]

Time:11-22

Although I'm relatively inexperienced in Java, I've been coding with Java long enough to know that this isn't normal behavior. Basically, the program is printing the text just fine, but the 'rand' variable is printing a conglomeration of numbers, characters, and letters, which are shown below.

I tried initializing the 'rand' variable into a nextInt() method, thinking that I would be producing the result of randomizing the result via a seed, but quickly understood that this would only generate a number within a range, not within a seed.

For context, I'm creating a while loop that continuously iterates a random number, based on the seed provided by the user, until the user types in the word 'stop' to end the loop.

How could I solve this?

Here's the code:

public static void WhileLoop(Scanner sc) {
        System.out.println("\nWHILE LOOP");

        System.out.println("Please enter a seed for the random number generator: ");
        int seed = sc.nextInt();

        Random rand = new Random(seed);

        int loopCounter = 0;
        String stop = "stop";
        String yes = "yes";

        while (loopCounter >= 0) {

            System.out.println("\nHere's your random number: "   rand);
            System.out.println("Would you like another number? Enter 'stop' to stop.");
            String answer = sc.next();
            loopCounter  ;

            if(answer.equals(yes)) {
                continue;
            }

            if(answer.equals(stop)) {
                break;
            }
        }

This is the result that's bugging me.

Here's your random number: java.util.Random@682a0b20
Would you like another number? Enter 'stop' to stop.

CodePudding user response:

To get a random number in java using the Random class, you need to call the rand.nextInt() method.

When it's printing the "java.util.Random@682a0b20", it is displaying the hashcode of the Random object that you created, which is just how computer tells each instance apart from another. It only displays the hashcode because there's no toString() method specific to the Random class to represent it as a string, when printed.

You might want to check out the java docs for the Random class.

Thanks @tgdavies, for correcting my statement about memory location/hashcodes.

  • Related