Cumulative Project 3 - I can't work out step 6

I’m completely stuck on step 6 on the Cumulative Project 3 exercise.

This is the instruction:

Use Math.random() to generate a random decimal value.
All Java objects have access to the built-in `Math` object.
And `Math` provides a method named `random()` which returns a randomly chosen `double` value greater than or equal to 0, but less than 1.
For example, some possible return values are `0.2312` , `0` , or `0.999999` .
Call `Math.random()` within `generateRandomNumber()` and save it to a local variable.

This is what I did:

public class MainActivity {

  public int generateRandomNumber(int max){
    double value =  Math.random();
    return (int)value;
  }
}

And this is the error message I get back:

Error: Main method not found in class MainActivity, please define the main method as:
   public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application

Am I doing something really stupid?

Welcome to the forums!

The error indicates that you’re missing a main method. You need at least one main method in a Java application. Make sure you’re following the instructions if they instruct you to construct a main method.

It hasn’t told me to create a main method as it says it is and when I create one it gives me a different error.

Here is the code with main method.

public class MainActivity {

  public int generateRandomNumber(int max){

    double value =  Math.random();

    return (int)value;

  }

  public static void main(String[] args){

    System.out.println(generateRandomNumber(6));

  }

}

and here is the new error message

MainActivity.java:10: error: non-static method generateRandomNumber(int) cannot be referenced from a static context
    System.out.println(generateRandomNumber(6));
                       ^
1 error

All good, I managed to fix it by doing.

public class MainActivity {

  public static int generateRandomNumber(int max){

    double value =  Math.random() * max;

    double number = value;

    int randomNumber = (int) number;

    return randomNumber;

  }

  public static void main(String[] args){

    System.out.println(generateRandomNumber(6));

  }

}
1 Like