tags:

views:

84

answers:

2

I'm very new to java and am working on my first Android app. I am using the webview demo as a template. I am trying to generate a random integer between 1 and 12 and then call a certain javascript function based on the result. Here's what I have:

int number = 1 + (int)(Math.random() * ((12 - 1) + 1));
number = (int) Math.floor(number);
String nextQuote = "javascript:wave" + number + "()";
mWebView.loadUrl(nextQuote);

So mWebView.loadUrl(nextQuote) will be the same as something like mWebView.loadUrl("javascript:wave1()")

I just want to know if what I have here is correct and will work the way I think it will. The application isn't responding as expected and I suspect this bit of code is the culprit.

+1  A: 

The key statement are as follows:

int number = 1 + (int)(Math.random() * ((12 - 1) + 1));
number = (int) Math.floor(number);

The first statement gives the answer you need, but in a rather cumbersome way. Lets step through what happens:

  1. ((12 - 1) + 1) is 12. (This is evaluated at compile time ... )

  2. Math.random() gives a double in the range 0.0D <= rd < 1.0D.

  3. Math.random() * 12 gives a double in the range 0.0D <= rd < 12.0D.

  4. The (int) cast converts the double to an int by rounding towards zero. In other words (int)(Math.random() * 12) will be a integer in the range 0 <= ri <= 11.

  5. Finally you add 1 giving an integer in the range 1 <= ri <= 12.

W**5 :-)

A simpler and clearer version would be:

private static Random rand = new Random();
...
int number = 1 + rand.nextInt(12);

The second statement is (as far as I can tell) a noop. It implicitly converts an int to a double, gets the double form of largest integer that is less or equal to that double, and converts that back to an int. The result will always be identical to the original int.

Stephen C
+1  A: 

Documention of Java Random Class http://java.sun.com/j2se/1.4.2/docs/api/java/util/Random.html

A good way to do this.

Random rand = new Random();               // does not have to be static but can be.
int number = rand.nextInt(12) + 1;        // 1 to 12 Must use 12 
                                          // Range is 0-11 add 1: 1-12
String nextQuote = "javascript:wave" + number + "()";
mWebView.loadUrl(nextQuote);

** from Java doc ** Method: public int nextInt(int n)

"Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)"

Calvin