根据If语句切换变量

时间:2014-06-05 18:34:47

标签: java string if-statement

我正在尝试创建一个程序,根据它来切换变量,在这种情况下,作为一个例子,你选择了什么样的动物。无需两次使用打印命令。

例如。我创建了两个字符串:

String thingsForDogs = "bone";
String thingsForCats = "yarn";

根据用户选择的动物,这些字符串会在打印出结果时相互切换。我不知道我会如何编码,但如果用户选择Cat作为他们的动物,他们会得到与他们选择Dog不同的输出。

我知道我可以这样做:

System.out.println("What animal do you want to be? Dog or cat?");
Scanner kb = new Scanner(System.in);
char choice = kb.nextLine().charAt(0);

if(choice == 'c' || choice == 'C')
        System.out.println("You have " + thingsForCats);
else if(choice == 'd' || choice == 'D')
        System.out.println("You have " + thingsForDogs);

但我仍然不知道如何做到这一点,而不必重复打印命令。我试图在一个打印命令中打印它,但是变量连同它被打印,将根据用户选择的动物进行切换。

3 个答案:

答案 0 :(得分:1)

您的代码没有任何问题。

您可以将其更改为开关:

System.out.print("You have ");
switch(choice){

    case "c":
    case "C":
        System.out.println(thingsForCats);
        break;
    case "d":
    case "D":
        System.out.println(thingsForDogs);
        break;
    default:
        // some errorhandling or Stuff
} 

答案 1 :(得分:1)

您可以使用HashMap来存储该数据,并一起避免使用if语句。

HashMap<char, String> map = new HashMap();
map.add('c', "yarn");
map.add('d', "bone");
...
// convert the input to lower case so you don't have to check both lower
// and upper cases
char choice = Character.toLowerCase(kb.nextLine().charAt(0));
System.out.println("You have " + map.get(choice));

答案 2 :(得分:0)

你有一行打印

String thingsForPet = "";
System.out.println("What animal do you want to be? Dog or cat?");
Scanner kb = new Scanner(System.in);
char choice = kb.nextLine().charAt(0);

thingsForPet = Character.toLowerCase(choice) == 'c' ? "yarn" : "bone";
System.out.println("You have " + thingsForPet);

考虑到您的comment,您可以将最后两行更改为:

if(choice == 'c' || choice == 'C') {
    thingsForPet = "yarn";
}
else {
    thingsForPet = "bone";
}
System.out.println("You have " + thingsForPet);