value zero generated numerously using random function() [duplicate] - java

This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 7 years ago.
/*This is my function code*/
Random random = new Random();
int randomInt = random.nextInt()%200;
String imgName = "img" + randomInt;
int ImageId = getResources().getIndentifier(imgName,"drawabale",getPackageName());
myImage.setImageResourse(ImageId);
Previously in my drawable folder there are
200 images already inserted using img1,img2.....img199
like nomenclature...
every time I call random function mention below to generated one
random number and form a string name starting from
"img" and some number. But most of time only 0 is generated by random function and id set to
image is display 0th image constantly..at some point it successfully display other images but most of time it generated zero value continuosly.
Thanks in Advance !

You can generate Random number with specific Range
Random r = new Random();
int randomInt = r.nextInt(maxVal - minVal) + minVal
For your example
int randomInt = r.nextInt(200 - 1) + 1
Will generate number between 1 to 199.

A random number generated by nextInt should be a multiple of 200 at random, i.e. one every 200 or so. This test suggests this is happening correctly:
public void test() {
Random random = new Random();
final int tests = 200000;
int twoHunderdIsAFactor = 0;
for (int i = 0; i < tests; i++) {
if (random.nextInt() % 200 == 0) {
twoHunderdIsAFactor += 1;
}
}
System.out.println("Tests = " + tests + " Hits = " + twoHunderdIsAFactor + " Proportion = " + (tests / twoHunderdIsAFactor));
}
prints Tests = 200000 Hits = 1012 Proportion = 197 - i.e. about 200 times for 200000 randoms.
Generating randoms in a specific range is dealt with in other answers.

Related

Generate random integer between 100 and 2000 in steps of 100 Java

Im currently trying to get a random integer between 100 and 2000 in steps of 100 like 300, 800, 1400 etc.
Thats what I found to get a random number between a range, but how do I manage to get a random number in steps of 100?
Random random = new Random();
int start = 100;
int end = 2000;
int result = random.nextInt(start - end) + start;
The problem is whether you want 2000 included or not. And whether the step size reaches 2000 exactly. The calculation just needs to include the step size:
Random random = new Random();
final int start = 100;
final int end = 2000;
final int step = 100;
int result = start + step * random.nextInt((end - start)/step); // end excl.
int result = start + step * random.nextInt((end - start)/step + 1); // end incl.
As already commented, it is probably more clear to base all on a random number between 1 and 20, and scale that up.
int result = (1 + random.nextInt(20)) * 100; // 100 upto 2000 by 100.

How toMake Math.random generate number between 1 and 1000? [duplicate]

This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 9 months ago.
So I'm trying to figure out how to print out a random number between 1 to 1000.
I tried:
double a = 1+ (Math.random()*1000);
System.out.println(a);
But when I try this i get numbers with a bunch of decimals. I do not want any decimals. Anyone can help? I want to get a value like 50 or 289 or 294. I do not want to get a number like 234.5670242
or 394.220345. Help if you can. will appreciate it. Thank you.
Try this:
public static void main(String args[])
{
// define the range
int max = 1000;
int min = 1;
int range = max - min + 1;
// generate random numbers within 1 to 1000
for (int i = 0; i < 1000; i++) {
int rand = (int)(Math.random() * range) + min;
// Output
System.out.println(rand);
}
}

How do I make a random int? [duplicate]

This question already has answers here:
How to get a random between 1 - 100 from randDouble in Java?
(6 answers)
Closed 2 years ago.
So I am trying to make 100 random integers from 1-100 print out. I can make doubles of this but not integers. Please show me how to make this into integers, here is the code.
for(i = 1; i <= 100; i++) {
double r = Math.random();
double in = r * 100;
System.out.print(in + ", ");
}
Please show me what I messed up or if I need to use an alternate technique for this
You can use Random object instead. from java.util package
Random random = new Random();
int value = random.nextInt(100);
Use ThreadLocalRandom:
for (int i = 1; i <= 100; i++) {
System.out.print(ThreadLocalRandom.current().nextInt(100) + ", ");
}
Import the class java.util.Random
Make the instance of the class Random, i.e., Random rand = new Random()
Invoke one of the following methods of rand object:
nextInt(upperbound) generates random numbers in the range 0 to upperbound-1.
nextFloat() generates a float between 0.0 and 1.0.
nextDouble() generates a double between 0.0 and 1.0
For example if you want to generate a random number between 1 to 100 the the code will be.
import java.util.Random;
Random r = new Random();
Int number = r.nextInt(100);
So variable number will be a random number between 1 to 100
Whats wrong is the statement double in = r * 100;
It must be
int b = (int) (Math.random()*100)%100; //range [0-99]
Just add 1 to b if you strictly want b in the range [1-100]

Displaying 500 random integers [duplicate]

This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 4 years ago.
I want to generate 500 random numbers and display them next to their indexes. I want the numbers to be 1 though 10. But when I run my code it only generates 13 random numbers and the numbers are greater than 10. Please help.
public class RandomStats {
public static void main(String[] args) {
int [] stats = new int [501];
int numRolls;
int outcome;
for (int i = 0; i <=500; i++ ){
outcome = (int) ( 10 * Math.random() + 1)
+ (int) ( 10 * Math.random () + 1);
stats[outcome] += 1;
}
for ( int i = 2; i <=500; i++) {
System.out.println(i + ": " + stats[i]);
}
}
}
While saving in the array, you are doing stats[outcome] += 1;, where your array is updated with same index again and again and thats the reason you only see ~13 values and rest as 0. I believe it should be stats[i] =outcome+ 1;

Making methods to print array (newbie in java) [duplicate]

This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 6 years ago.
I am kind of new in Java, and I got assigned some exercises. Any idea how to this small problem?
create an array consisting of 100 random integers in the range 100 to 500, including the end points.
make a method to print the array, 5 numbers per line, with a space between each.
make a method to print the smallest number in the array.
So far this is what i got for the first 2 parts but i doesn't seem work, help please, sorry for asking such dumb questions...
package randomhundred;
import java.text.DecimalFormat;
public class RandomHundred {
public static void main(String[] args) {
//setting the 100 array
int rand [] = new int [100];
double numb;
DecimalFormat dec = new DecimalFormat("0");
for(int i=0; i<rand.length; i++){
numb = Math.random() * ( 500 - 100 );
}
}
public static int arai (){
return System.out.print(" " + dec.format(numb) + " ");
}
}
Let's get step 1 right.... generating 100 random values.
Your process is nearly there.... but:
it does not generate an int value so you can't store it in an int[] array.
it will never generate the value 500.
To convert the random number to an integer, try the following:
int numb;
....
numb = (int)(Math.random() * ( 500 - 100 ));
but, this will not generate the value 500 (because 500 - 100 is 400, but, there's actually 401 numbers you need to generate....), so change it to (see How do I generate random integers within a specific range in Java?):
numb = 100 + (int)(Math.random() * ( (500 - 100) + 1))
Now we have random numbers between 100 and 500 (inclusive), you need to store them in your array now:
rand[i] = numb;
Once you have that working, come back and we can tackle the other problems.
until then, you can print out your array with:
System.out.println(Arrays.toString(rand)); // Arrays is java.util.Arrays
I'll try to supply some pseudo code for your problem:
// Task 1
Declare array of 100 ints (I will relate to 100 later on with n).
Fill array with random integers between 100 and 500 including borders
Hint code for this: 100 + new Random().nextInt(401), 401 as the upper bound is exclusive which makes the max result: 100 + 400 -> 500 and the minimum: 100 + 0 = 100. Even though this will generate the 100 numbers it will be faster if you store the random instance somewhere and re-use it, but that's an optimization step.
// Task 2
for i = 0; i < n; i++
print integer from array
add space
if i is divisible by 5 then
add new line
end-if
end-for
//Task 3
declare a min of the maximum value which is possible: in this case your maximum random number of 500
loop through the list checking for smaller numbers
after loop has finished print the last number
I hope this is clear enough for you get an idea on how this could be done.
Ad. 1
For the sake of completeness (it's been explained by others):
for(int i=0; i<rand.length; i++){
rand[i] = 100 + (int)(Math.random() * ( 401 ));
}
Ad. 2
This is wrong:
public static int arai (){
return System.out.print(" " + dec.format(numb) + " ");
}
Return type is int, but System.out.print() doesn't return anything, so change int to void and remove return keyword. Next, you'll need to iterate through the whole array:
public static void arai (){
for (int i=0; i< 100; i++) {
//this is modulo, which means that if i divided by 5 has no remainder, print next line
//eg. 5%2 = 1, because 2*2 + 1 = 5
//5%3 = 2 and so on, read here http://en.wikipedia.org/wiki/Modulo_operation
if (i%5 == 0) {
System.out.println();
}
//finally, print each value from rand array
System.out.print(rand[i] + " ");
}
}
Ad. 3
Try yourself, and comeback if you have issues, but follow Johnnei's advice of finding the smallest number.
NOTE: you also need to make the rand array declaration global, so that it's available to arai() method.

Categories

Resources