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

My java code is only outputting 0 when I use multiple classes and methods

I want to generate a random number between 1 and 6 and print it, but I keep getting 0 for the output. When I try putting the code in the Main class and main method only, it works, but not when I do it as I have below:

class Main {
  public static void main(String[] args) {

    System.out.println(Dice.randomRoll());

  }
}

This is my Main class above, Dice class below.

import java.util.*;

class Dice {

  private static int randomRoll;  

  public static void roll() {
     Random r = new Random();
     int low = 1;
     int high = 7;
     int randomRoll = r.nextInt(high-low) + low;
  }  

  public static int randomRoll() {
    return randomRoll;
  }

}

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

>Solution :

Method roll is never called, so the value of randomRoll is never changed. Try calling roll(); first in the randomRoll method.

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