简体   繁体   中英

Multiple else if Statements Fix

I have a random name generator using a simple Random system, basically it gets a number 1 - 10 then there are a bunch of is statements for the numbers

    if(f == 1)
    {
        fst = "Daws";
    }
    else if(f == 2)
    {
        fst = "Rom";
    }
    else if(f == 3)
    {
        fst = "Trout";
    }
    else if(f == 4)
    {
        fst = "Bally";
    }
    else if(f == 5)
    {
        fst = "Kuu";
    }
    else if(f == 6)
    {
        fst = "Invery";
    }
    else if(f == 7)
    {
        fst = "Dragon";
    }
    else if(f == 8)
    {
        fst = "Bam";
    }
    else if(f == 9)
    {
        fst = "Laen";
    }
    else if(f == 10)
    {
        fst = "Glen";
    }

is there a way I could condense this? any tips?

You could use a switch statement.

switch (f) {
case 1: fst = "Daws"; break;
case 2: fst = "Rom"; break;
...
}

Or, even better, create a lookup array:

String[] strs = { "Daws", "Rom", ... };

and use it as follows:

fst = strs[f-1];  // -1 since your random number starts from 1.

You can do

// a condensed way of doing FSTS = { "Daws", "Rom", ... };
static final String[] FSTS = 
             "Daws,Rom,Trout,Bally,Kuu,Invery,Dragon,Bam,Laen,Glen".split(",");

// later
fst = FSTS[f-1];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM