I have set of numbers like [1000,2000,3000,4000]
Now I have to select one from above this numbers in Java how to do it? help me
How to use random method to select numbers?
Page 1 of 14 Replies - 661 Views - Last Post: 27 January 2013 - 11:07 PM
Replies To: How to use random method to select numbers?
#2
Re: How to use random method to select numbers?
Posted 25 January 2013 - 04:46 AM
Well, you have those numbers in an array I presume?
Here's how you go about it...
First you need to import the following...
Then, you need to generate a random number something like this.
Now use the index variable to call your array value.
Edit :Well, this was just my take on solving the problem...I believe there are much better methods to go about this problem.
regards,
Raghav
Here's how you go about it...
First you need to import the following...
java.util.Random;
Then, you need to generate a random number something like this.
Random num = new Random(); //code for getting a value from 0 to 3 and store it as index.
Now use the index variable to call your array value.
Edit :Well, this was just my take on solving the problem...I believe there are much better methods to go about this problem.
regards,
Raghav
This post has been edited by raghav.naganathan: 25 January 2013 - 04:51 AM
#3
Re: How to use random method to select numbers?
Posted 25 January 2013 - 05:00 AM
#4
Re: How to use random method to select numbers?
Posted 25 January 2013 - 05:27 AM
raghav.naganathan, on 25 January 2013 - 01:46 PM, said:
[code]java.util.Random;
Then, you need to generate a random number something like this.
Random num = new Random();
you're almost right, but your code is incomplete.. you have to add something like this:
int randomArrayIndex = num.nextInt(ar.length); // where ar is a typical fixed size array []
or
int randomArrayIndex = num.nextInt(ar.size()); // where ar is an ArrayList
or, without importing Random:
int randomArrayIndex = (int) (Math.random() * b.length); // respectively * b.size() for ArrayList
This post has been edited by ccdan: 25 January 2013 - 05:30 AM
#5
Re: How to use random method to select numbers?
Posted 27 January 2013 - 11:07 PM
Thanks I hope this works
Page 1 of 1

New Topic/Question
Reply



MultiQuote



|