String.userName
String.userName

Reputation: 53

How to randomise an output

Say I had 3 outputs:

System.out.println("output 1");
System.out.println("output 2");
System.out.println("output 3");

How would I make it so only one of the outputs printed, and the one that was printed is random every time?

Upvotes: 0

Views: 615

Answers (6)

user2030471
user2030471

Reputation:

This is a simple implementation:

String[] str = { "Output1", "Output2", "Output3" };
Random r = new Random();
System.out.println(str[r.nextInt(3)]);

Upvotes: 1

eliot
eliot

Reputation: 1329

You can accomplish this with Math.random().

First, generate a random number between 0 and 3:

int randomNum = (int)Math.random() * 3;

Next, use if-else statements to choose which statement to print:

if(randomNum == 0)
   //print case 1
else if(randomNum == 1)
   //print case 2
else //print case 3

Upvotes: 3

pavja2
pavja2

Reputation: 387

The most conceptually simple way to do this is probably to create a random integer and use a switch statement and cases to select each output.

Upvotes: 1

Mike Samuel
Mike Samuel

Reputation: 120516

// Collect all the possible outputs.
String[] outputs = new String[] { "output 1", "output 2", "output 3" };
// Use the core library class java.util.Random to get a source of pseudo-randomness.
Random random = new Random();
// Pick one and print it.
System.out.println(outputs[random.nextInt(outputs.length)]);

nextInt returns a pseudo-random number uniformly distributed between 0 and its argument - 1.

Since Random is pseudo-random, if you need the output to be unguessable even by someone who observes many of your random choices, use SecureRandom instead.

Upvotes: 5

ldam
ldam

Reputation: 4585

You can use the java.util.Random class to generate a random int and then just use a simple if statement to print the corresponding output.

Upvotes: 2

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70929

Put the strings to print in a String array and then generate random number up to the size of this array. Print the String at the index generated.

Upvotes: 2

Related Questions