英文:
I want to avoid the amount of if-statements I have
问题
在我的代码中,我有用户输入和我想要向他们打印的内容。
例如:
如果他们的输入是"1",则输出"one",
如果他们的输入是"2",则输出"two",
如果他们的输入是"3",则输出"three",
如果他们的输入是"4",则输出"four",
诸如此类。我该如何做到这一点,但又不使用那么多的if语句。
英文:
In my code I have the user input and something I want printed to them.
For example:
If their input is "1", output "one",
If their input is "2", output "two",
If their input is "3", output "three",
If their input is "4", output "four"
And so on. How would I be able to make this but without using so many if-statements.
答案1
得分: 2
你可以使用 map
来实现这个功能。
注意:JDK9+
中的 Map.of()
方法。
public static void main(String[] args) {
Map<String, String> map = Map.of("1", "one", "2", "two", "3", "three", "4", "four");
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
System.out.println(map.get(input));
scanner.close();
}
英文:
You can use map for this
Note: Map.of()
from JDK9+
public static void main(String[] args) {
Map<String, String> map = Map.of("1", "one", "2", "two", "3", "three", "4", "four");
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
System.out.println(map.get(input));
scanner.close();
}
答案2
得分: 1
使用关键字 'switch'
switch (输入的值) {
case "1": 输出 "one";
case "2": 输出 "two";
case "3": 输出 "three";
case "4": 输出 "four";
}
我保留了你之前使用的伪代码部分,这并不是可运行的代码。
英文:
use keyword 'switch'
switch (their input) {
case "1": output "one";
case "2": output "two";
case "3": output "three";
case "4": output "four";
}
I kept the pseudo langage stuff you were using, this is not a working code
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论