【发布时间】:2014-06-05 18:34:47
【问题描述】:
我正在尝试创建一个程序,它会根据您选择的动物来切换变量,在这种情况下,作为示例。无需使用两次打印命令。
例如。我创建了两个字符串:
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);
但我仍然不知道如何做到这一点,而不必重复打印命令。我试图在一个打印命令中打印所有内容,但是变量连同它被打印,被切换,这取决于用户选择什么作为他们的动物。
【问题讨论】:
-
仅供参考 - 您的代码中有一些错误。 nextLine 应该是 nextLine()。您在 IF-ELSE 语句中列出了 thingsForCats 两次。
-
我不确定你的问题到底是什么。您发布的代码可以使用(
kb.nextLine应为kb.nextLine()除外)。 -
很抱歉,应该更清楚地说明这一点,我用
nextLine()修复了这个错误。我的意思是不必重复打印命令。一站式打印命令。
标签: java string if-statement