简体   繁体   English

如果语句修复,则其他多个

[英]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 我有一个使用简单Random系统的随机名称生成器,基本上它得到一个数字1-10,然后有一堆is语句用于数字

    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语句。

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];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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