2014-10-18 40 views
-6

如何将用户输入的数字替换为其在打印行中选择的实际对应字符串。如何将整数重命名为字符串

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

它更长,但我不得不减少它。

+2

将int分析为String:'String.parseInt(myInt)'。或者简单地打印int,'System.out.println(“”+ myInt);' – 2014-10-18 21:36:20

+1

...或者'String foo = String.valueOf(1);'请先搜索 - 例如:http:// stackoverflow.com/questions/4105331/how-to-convert-from-int-to-string – Trinimon 2014-10-18 21:38:11

+0

你在问什么? 'String.valueOf(int)','Integer.parseInt(String)'或其他? – 2014-10-18 21:39:54

回答

0

哪种编程语言?

爪哇:

String s = String.valueOf(123); 
String s = 123 + ""; 

C++

int a = 10; 
stringstream ss; 
ss << a; 
string str = ss.str(); 

的C++ 0x

std::string s = std::to_string(42); 

C#

string s = myInt.ToString(); 
+0

好的,这里是我的代码https://gist.github.com/anonymous/a896b9f3ea0ba7449b25我需要用打印行中的相应字符串 – John 2014-10-18 21:44:42

+3

来替换数字,使用它作为题。你原来的问题很糟糕。 – tom 2014-10-18 21:45:20