0
How to execute specific statements based on a random number generation? I'm using Java.
8 Answers
+ 6
Alessio: Define your Strings and then use Math.random to choose the String.
E.g.
// random int from 0 to 9
int rand = (int)(Math.random() * 10);
switch (rand) {
case 0: // do something with 1. String
break;
// same for cases from 1 to 9
};
Consider using e.g. HashMap, that allows to store key/value pairs so you could access your String values by an int key. You only need to pass the rand from example above:
map.get(rand);
No need for switch statement then.
+ 5
Use Math.random() and if/then/else?
http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#random()
What do you want to do?
+ 4
Math.random() is a possibility then.
+ 1
Thanks for your help.
+ 1
I really appreciate your help. Thank you.
0
I'm creating a game and I want to randomly generate the enemy response, like if he is going to attack, or use a potion,etc..
0
i can use the same method for string var?
0
thanks Tashi I have solved so
String[] coseDaFare= {"1","2","3"}
Random rand = new Random(); \\ random
int casuale= rand.nextInt(coseDaFare.length);
i think is the same, or not?