user3367199
user3367199

Reputation: 19

Random Number between -.5 and .5

I'm trying to get a random number to be generated between -.5 and .5, but I'm running into some errors

Rng.java:11: error: ';' expected
    double randomWithRange(double min, double max)
                          ^
Rng.java:11: error: <identifier> expected
    double randomWithRange(double min, double max)
                                      ^
Rng.java:11: error: not a statement
    double randomWithRange(double min, double max)
                                              ^
Rng.java:11: error: ';' expected
    double randomWithRange(double min, double max)

and here's the code

class Rng
{

double min = -0.5;
double max = 0.5;

public static void main(String[] args) 
{
double randomWithRange(double min, double max)
    {
    double range = (max - min);     
    return (Math.random() * range) + min;
    }


}
}

Can anyone help me out?

Upvotes: 1

Views: 260

Answers (2)

Florent Bayle
Florent Bayle

Reputation: 11920

The problem is that your method randomWithRange() is inside your main() method, this is not permitted in java.

Try something like that:

public static void main(String[] args) 
{
    double min = -0.5;
    double max = 0.5;
    System.out.println(randomWithRange(min, max));
}

static double randomWithRange(double min, double max)
{
    double range = (max - min);     
    return (Math.random() * range) + min;
}

You may also want to have a look at this page in the Beginners' resources section.

Upvotes: 4

Jack
Jack

Reputation: 133577

You are declaring a method inside another method:

public static void main(...) {
  double randomWithRange(...) {
  }
}

This is not allowed in Java. You must declare them separately:

public static void main(...) {
  double randomValue = randomWithRange(...);
}

static double randomWithRange(...) {

}

Mind that you have to declare randomWithRange static (as main) if you want to call it from your main method.

Upvotes: 4

Related Questions