Reputation: 39
I (beginner) want to print random names (string) from an array. Although this code is working just fine, I think this is not the right way to do this. Any help would be highly appreciated.
package com.test;
public class Main {
public static void main(String[] args) {
//print random names from the array
String name[] = new String[10];
name[0] = "John";
name[1] = "James";
name[2] = "Ashley";
name[3] = "Robert";
name[4] = "Bradley";
name[5] = "Jennifer";
name[6] = "Stewart";
name[7] = "Natalie";
name[8] = "Austin";
name[9] = "Scarlette";
int random = (int) (Math.random() * 9);
switch (random) {
case 0:
System.out.println(name[0]);
break;
case 1:
System.out.println(name[1]);
break;
case 2:
System.out.println(name[2]);
break;
case 3:
System.out.println(name[3]);
break;
case 4:
System.out.println(name[4]);
break;
case 5:
System.out.println(name[5]);
break;
case 6:
System.out.println(name[6]);
break;
case 7:
System.out.println(name[7]);
break;
case 8:
System.out.println(name[8]);
break;
case 9:
System.out.println(name[9]);
break;}
}
}
Upvotes: 1
Views: 177
Reputation: 1449
You could use the nextInt(int) method of Java's Random class. It takes an integer as a parameter and returns a random integer that can range from 0 up to (but not including) your parameter. This makes it perfect for accessing a random index in an array.
Random random = new Random()
System.out.println(name[random.nextInt(name.length)]);
Upvotes: 0
Reputation: 11567
This would be a better way.
Remove the switch loop with
System.out.println(name[random]);
Also you can make the initialization and declaration part in a single line of code. Refer
And whole code will become
package com.test;
public class Main {
public static void main(String[] args) {
String[] name = {"John","James","Ashley","Robert","Bradley","Jennifer","Stewart","Natalie","Austin","Scarlette"};
//generating random number between 0 and name.length
int random = (int) (Math.random() * name.length);
//print random name from the array
System.out.println(name[random]);
}
}
Upvotes: 11