John
John

Reputation: 31

How do I replace the user inputed integer with the corresponding String

How do I replace the number that the user inputs as their choice with the actual corresponding string that their choice means in the print line. My code is longer but I had to trim it down.

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 + ".");
  }
}

These are supposed to be three groups each numbered 1-4 but the formatting keeps changing them.

  1. Magic User
  2. Fighter
  3. Thief
  4. Druid

  5. Steel plate – Armor Class 10

  6. Chain mail – Armor Class 5
  7. Leather armor – Armor Class 3
  8. A robe – Armor Class 1

  9. Sword

  10. Short sword
  11. Scimitar
  12. Dagger

Upvotes: 1

Views: 57

Answers (1)

libik
libik

Reputation: 23029

Map is good in storing values like this.

For example this code :

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

Has this output:

You are: Mage

You can use map for iteration too :

    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());
    }

Has this output :

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

Upvotes: 1

Related Questions