Java 根据If语句切换变量

Java 根据If语句切换变量,java,string,if-statement,Java,String,If Statement,我试着创建一个程序,它根据你选择的动物来切换变量。无需使用打印命令两次 比如说。我创建了两个字符串: String thingsForDogs = "bone"; String thingsForCats = "yarn"; 这些字符串在打印结果时会相互切换,这取决于用户选择的动物。我不知道该如何编码,但如果用户选择猫作为他们的动物,他们将得到不同于选择狗的输出 我知道我可以这样做: System.out.println("What animal do you want to be? Dog

我试着创建一个程序,它根据你选择的动物来切换变量。无需使用打印命令两次

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

String thingsForDogs = "bone";
String thingsForCats = "yarn";
这些字符串在打印结果时会相互切换,这取决于用户选择的动物。我不知道该如何编码,但如果用户选择猫作为他们的动物,他们将得到不同于选择狗的输出

我知道我可以这样做:

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

但我仍然不知道如何才能做到这一点,而不必重复print命令。我试图在一个打印命令中打印所有内容,但打印时随附的变量会根据用户选择的动物进行切换。

您的代码没有问题

您可以通过开关将其更改为:

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
} 

您可以使用
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));
HashMap map=newhashmap();
添加('c',“纱线”);
地图。添加('d','bone');
...
//将输入转换为小写,这样就不必同时检查两个小写
//和大写字母
char choice=Character.toLowerCase(kb.nextLine().charAt(0));
System.out.println(“您有”+map.get(选项));

这是一行打印

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);
考虑到您的需求,您可以将最后两行更改为:

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

仅供参考-您的代码中有一些错误。nextLine应该是nextLine()。你在IF-ELSE声明中列出了两个原因。我不确定你的问题到底是什么。您发布的代码可以正常工作(除了
kb.nextLine
应该是
kb.nextLine()
)。很抱歉,我应该更清楚地说明这一点,我用
nextLine()
修复了这个错误。我的意思是不必重复打印命令。一个打印命令,我试试。我刚刚接触Java,所以我还没有学过HashMaps之类的东西,但我知道要改成小写,我忘了如何正确使用它。