1

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?

  • 4
    Java doesn't allow you to nest a method inside another. Move `randomWithRange` out of `main`. – ajb Mar 11 '14 at 00:37

2 Answers2

4

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.

Florent Bayle
  • 11,520
  • 4
  • 34
  • 47
4

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.

Community
  • 1
  • 1
Jack
  • 131,802
  • 30
  • 241
  • 343