vendredi 14 mai 2021

How can I call a method from a separate class that contains a randomized value and use that value to print in my main class?

I am new to coding and I am trying to figure out how to call a method from a separate class and use it in my main class. I know that it is easier to do it in the main class but I was asked to do it in a separate class. The random number that is printed to range from 1 to 3 but using this method I just get 0.

here's the main class:

package example;

public class Example {

    public static int number;
    
    public static void main(String[] args) {
        
        otherClass a = new otherClass();
        a.assignNumber();
         System.out.println(number);
                 
         
    }
    
}

and my separate class:

package example;

import java.util.Random;

public class otherClass {
     public int assignNumber(){
        Random num = new Random();
        int number = num.nextInt(4) + 1;
        return number;
    }
}



Aucun commentaire:

Enregistrer un commentaire