Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does the Random method produce the name of the method when being printed? [Java]

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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 memory location of the Random object that you created, which is just where the computer stores its data. It only displays the memory location because there’s no toString() method attributed with the class to represent it as a string, when printed.

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading