Ole
Ole

Reputation: 13

How do I define multiple variables within a switch by random?

I'm a noob in Java and need some help with this. I wonder how to get a random name for each of the nameOne, nameTwo and NameThree strings without duplicating the whole switch statement. Can someone please give me an advice on how to do this without bloating up my code? My actual name list is very long.

public class multipleNamesPicker {public static void main(String[] args) {

    String nameOne = null;
    String nameTwo = null;
    String nameThree = null;
    char gender1 = 'a'; 
    char gender2 = 'a';
    char gender3 = 'a';

    byte randomNumber1 = (byte)(Math.random()*2+1);
    switch(randomNumber1) {
      case 1: gender1 = 'w';
      case 2: gender1 = 'm';
    }

    byte randomNumber2 = (byte)(Math.random()*5+1);
    if(gender1 == 'w'){
        switch(randomNumber2) {
           case 1: nameOne = "Edna";
           case 2: nameOne = "Martha";
           case 3: nameOne = "Berta";
           case 4: nameOne = "Margaret";
           case 5: nameOne = "Anna";
        }
     }

     else{
        switch(randomNumber2) {
          case 1: nameOne = "Peter";
          case 2: nameOne = "Paul";
          case 3: nameOne = "Pablo";
          case 4: nameOne = "Henry";
          case 5: nameOne = "George";
        }
     }

    System.out.println(nameOne + ", " + nameTwo + " and " + nameThree);}
}

Upvotes: 0

Views: 52

Answers (1)

GBlodgett
GBlodgett

Reputation: 12819

One easy way would be to put them in two Array's (One for female names and one for male names) and then have something like

if(gender1 == 'w'){
    nameOne = femaleNames[randomNum];
}

Where femaleNames is your Array of female names and randomNum is your random number. Just make sure randomNum is within bounds of your Array

Upvotes: 1

Related Questions