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.
The key statement are as follows:
The first statement gives the answer you need, but in a rather cumbersome way. Lets step through what happens:
((12 - 1) + 1)is12. (This is evaluated at compile time … )Math.random()gives adoublein the range0.0D <= rd < 1.0D.Math.random() * 12gives adoublein the range0.0D <= rd < 12.0D.The
(int)cast converts thedoubleto anintby rounding towards zero. In other words(int)(Math.random() * 12)will be a integer in the range0 <= ri <= 11.Finally you add
1giving an integer in the range1 <= ri <= 12.W**5🙂A simpler and clearer version would be:
The second statement is (as far as I can tell) a noop. It implicitly converts an
intto adouble, gets thedoubleform of largest integer that is less or equal to thatdouble, and converts that back to anint. The result will always be identical to the originalint.