Cumulative Project 3 - What's wrong with my method?

Hi all,

I’m currently completing the Cumulative Project 3 of the build android apps with Java course.

It has tasked me with creating a method that returns a random number, which I have written as follows:

public int generateRandomNumber(int max){

   int value = (int) (Math.random() * max);

   double number = (double) value;

  return number;

}

Yet, when I run the code I receive the following error:

MainActivity.java:7: error: incompatible types: possible lossy conversion from double to int
return number;

Where am I going wrong here?

You can see the task by following this link:

Hey there,

I may be wrong but aren’t you indicating that your return type must be an integer?

public int

However, you’re attempting to return a double (number).

That would explain the error message: “lossy conversion from double to int”.

Hey :wave:

You’re correct, however the task asks me to store the result of Math.random() in a local double variable. Which is why I am using a cast. It’s likely I’m misunderstanding the requirement, though I’d argue Codecademy are causing more confusion splitting the task into 3 separate parts.

Would it be possible to bypass the second step, meaning

  • Store the result of Math.random() in a double
  • Return the value as an int

?

Other question, do you explicitly have to return an int?


Last, did you try returning number as an int?

I have made some changes to my code see below:

double value = Math.random() * max;
   double number = (double) value;
   int result = (int) number;
   return result;

This now throws a new error:

Error: Main method not found in class MainActivity, please define the main method as:

This is baffling as it is defined in Main.java

That would work, but I think you’re overcomplicating things.

Wouldn’t this just work?

double value = Math.random() * max;
return (int) value;

Ah man why is it always so obvious! Yeah this is one of my biggest challenges with coding my brain tends to look for the most complicated answer.

2 Likes