Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android Build a Simple Android App (retired 2014) Learning the Language Objects and Random Numbers

Can someone help please

Q. Declare a String variable named intAsString. Convert the randomNumber integer to a String value and store it in the intAsString variable. Hint: Use the toString() method of the Integer class.

I have watched the video before hand several times and still I cannot work this out. Any help would be much appreciated as I am new to this and like to learn quickly. Thanks

So far I have:

Random randomGenerator = new Random();

int randomNumber = randomGenerator.nextInt(10);

7 Answers

Is this for JavaScript?

Hi, Yes sorry I forgot to mention.

Thanks for your help but that's just confused me. I haven't been taught about anything like you've just shown me.

Well, it's general JavaScript, but i'll step it through for you:

  1. var randomNumber = Math.random();

This creates a variable called randomNumber and stores a random number (0 to 0.999) in that variable. JavaScript variables the random function from the Math object to create a random number (a decimal actually) from 0 to 0.99999.

So if you want a random number between 1 to 10 let's say, you want to do this: (Math.random() * 10) + 1). This looks confusing, but if you take it apart its not too bad.

Since you are taking a random decimal and multiplying it by 10, you are giving it a maximum value of 9 and a minimum value of 0. Since you want it from 1-10, you just add 1 to the final result.

  1. var intAsString = randomNumber.toString();

This variable (randomNumber), contains a decimal value, so since you want to convert it to a string, you use the toString() method of a integer (or decimal - works the same) and store that value in your new variable intAsString. So it really has the exact same value, it just stores it as String instead of number, which means you can no longer use it in mathematical calculations (add, subtract, etc.)

  1. alert("random number: " + intAsString);

Using an alert box to display the value.


Great!! Thanks for the explanation that helped a lot, I think you've given me a more advanced way to solve it.

Thanks for the Links also very helpful!

Glad to help :)