[英]Switch Variables Depending on If Statement
我正在尝试创建一个程序,在该程序中,您将根据所选择的动物来切换变量。 不必两次使用print命令。
例如。 我创建了两个字符串:
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));
在那里,一行打印
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.