如何用相应的String替换用户输入的整数

时间:2014-10-18 23:11:54

标签: java

如何将用户输入的数字替换为其选择在打印行中所用的实际相应字符串。我的代码更长,但我不得不削减它。

import java.util.Scanner; 

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

  {

    String name;
    int userCharacter;
    int armorChoice;
    int weaponChoice;


    Scanner input = new Scanner(System.in); 

    System.out.println("Please enter your name");
    name = input.nextLine();
    { 
    System.out.println("Please select the character you would like to play:" + '\n' + "1 for Magic User" + '\n' + "2 for Fighter" + '\n' + "3 for Thief" + '\n' + "4 for Druid" );
    userCharacter = input.nextInt();

    System.out.println("Please select your Armor Type:" + '\n' + "1 for Steel plate – Armor Class 10" + '\n' + "2 for Chain mail – Armor Class 5" + '\n' + "3 for Leather armor – Armor Class 3" + '\n' + "4 for A robe – Armor Class 1");
    armorChoice = input.nextInt();

    System.out.println("Please choose a Weapon:" + '\n' + "1 for Sword" + '\n' + "2 for Short Sword" + '\n' + "3 for Scimitar" + '\n' + "4 for Dagger");
    weaponChoice = input.nextInt();


    System.out.println("Hello " + name + "! You chose to play a " + userCharacter + "." + '\n' + "Your armor is" + armorChoice + "." + '\n' + "You will be fighting with a " + weaponChoice + ".");
  }
}

这些应该是三组,每组编号为1-4,但格式不断改变它们。

  1. 魔术用户
  2. 战斗机
  3. 钢板 - 装甲等级10

  4. 锁子甲 - 盔甲等级5
  5. 皮甲 - 盔甲3级
  6. 长袍 - 盔甲等级1

  7. 短剑
  8. 弯刀
  9. 匕首

1 个答案:

答案 0 :(得分:1)

Map可以很好地存储这样的值。

例如这段代码:

    int playerCharacter;

    Map<Integer, String> characters = new HashMap<Integer, String>();
    characters.put(1, "Fighter");
    characters.put(2, "Mage");
    characters.put(3, "Rogue");        

    playerCharacter = 2; //This is what you get from input

    System.out.println("You are: " + characters.get(playerCharacter));

有这个输出:

You are: Mage

您也可以使用map进行迭代:

    System.out.println("Please select the character you would like to play:");
    for (Entry<Integer, String> character : characters.entrySet()) {
        System.out.println(character.getKey() + ": " + character.getValue());
    }

有这个输出:

Please select the character you would like to play:
1: Fighter
2: Mage
3: Rogue