将多个字符串转换为一个

时间:2018-08-20 01:01:31

标签: java

我正在尝试将多个字符串从NPC转换为一个简单的对话。基本上,我想做的是列出玩家拥有200M经验的所有技能,并将其输出到NPC对话中。

OLD

        if (componentId == OPTION_4) {
            sendNPCDialogue(npcId, 9827, "You can prestige: "+maxedSkills()+"");
        }

private String maxedSkills() {
    return ""+attackMax()+""+strengthMax()+""+defenceMax()+"";
}

public String attackMax() {
    if (player.getSkills().getXp(Skills.ATTACK) == 200000000)
    return "Attack, ";
    else
    return "";
}

public String strengthMax() {
    if (player.getSkills().getXp(Skills.STRENGTH) == 200000000)
    return "Strength, ";
    else
    return "";
}

public String defenceMax() {
    if (player.getSkills().getXp(Skills.DEFENCE) == 200000000)
    return "Defence, ";
    else
    return "";
}

有了该代码,我就可以使用它,但是由于有25种不同的技能,因此需要添加很多代码。我将如何创建一种使所有技能都被引用的方法?以下是所有技能名称:

public static final String[] SKILL_NAME = { "Attack", "Defence", "Strength", "Constitution", "Ranged", "Prayer",
        "Magic", "Cooking", "Woodcutting", "Fletching", "Fishing", "Firemaking", "Crafting", "Smithing", "Mining",
        "Herblore", "Agility", "Thieving", "Slayer", "Farming", "Runecrafting", "Hunter", "Construction",
        "Summoning", "Dungeoneering" };

新的和有效的(用于攻击/强度/防御):

public static final int[] SKILL_TYPE = {Skills.ATTACK, Skills.STRENGTH, Skills.DEFENCE};

public String maxedSkills() { 
    StringBuffer sb = new StringBuffer();
    for(int i = 0; i < SKILL_TYPE.length; i++) { 
        if (player.getSkills().getXp(i) == 200000000) {
        if(sb.length()>0) sb.append(", ");
        sb.append(Skills.SKILL_NAME[i]);
        }
      }
    if(sb.length()>0) sb.append(".");
    return sb.toString();
}

2 个答案:

答案 0 :(得分:1)

最简单的方法是拥有一个将Skill类型作为输入的参数化方法。这是它的样子:

public String skillMax(Skills skill) {
    if (player.getSkills().getXp(skill) == 200000000)
    return skill.getName() + ", ";
    else
    return "";
}

接下来要做的是为name枚举中的技能提供一个Skills。这样的事情应该起作用:

public enum Skills {
    DEFENSE("Defense"), ...;
    private String name;
    Skills(String name) { this.name = name; }
    String getName() { return this.name; }
}

答案 1 :(得分:0)

使用StringBuffer(线程安全)或StringBuilder并执行类似的操作。

....
public static final Skills[] SKILL_TYPE = {Skills.Attack, Skills.Defence, ...};

public String getBigString() { 
    StringBuffer sb = new StringBuffer();
    int nSkills = 0, lSkill = 0;
    for( int i = 0; i < SKILL_TYPE.length; i++ )
      { 
      if( player.getSkills().getXp(SKILL_TYPE[i]) == K_SOMELEVEL ) {
        if(nSkills > 0) sb.append(", ");
        lSkill = sb.length(); // track position of last skill in string
        nSkills += 1;
        sb.append(SKILL_NAME[i]);
        }
      }
    if( nSkills > 0 ) 
      { 
      if( nSkills > 1 ) sb.insert( lSkill, "and ");
      sb.append(".");
      }
    return sb.toString();
}