0

How to execute specific statements based on a random number generation? I'm using Java.

18th Feb 2017, 6:38 AM
Abd Elrahman Omar
Abd Elrahman Omar - avatar
8 Respuestas
+ 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.
24th Feb 2017, 5:31 PM
Tashi N
Tashi N - avatar
+ 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?
18th Feb 2017, 8:39 AM
Tashi N
Tashi N - avatar
+ 4
Math.random() is a possibility then.
18th Feb 2017, 9:11 AM
Tashi N
Tashi N - avatar
+ 1
Thanks for your help.
18th Feb 2017, 9:14 AM
Abd Elrahman Omar
Abd Elrahman Omar - avatar
+ 1
I really appreciate your help. Thank you.
24th Feb 2017, 6:04 PM
Abd Elrahman Omar
Abd Elrahman Omar - avatar
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..
18th Feb 2017, 8:51 AM
Abd Elrahman Omar
Abd Elrahman Omar - avatar
0
i can use the same method for string var?
18th Feb 2017, 12:59 PM
Alessio Farroni
Alessio Farroni - avatar
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?
24th Feb 2017, 7:18 PM
Alessio Farroni
Alessio Farroni - avatar