我想避免我现在拥有的大量if语句。

huangapple go评论99阅读模式
英文:

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&lt;String, String&gt; map = Map.of(&quot;1&quot;, &quot;one&quot;, &quot;2&quot;, &quot;two&quot;, &quot;3&quot;, &quot;three&quot;, &quot;4&quot;, &quot;four&quot;);
        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 &quot;1&quot;: output &quot;one&quot;;
  case &quot;2&quot;: output &quot;two&quot;;
  case &quot;3&quot;: output &quot;three&quot;;
  case &quot;4&quot;: output &quot;four&quot;;
}

I kept the pseudo langage stuff you were using, this is not a working code

huangapple
  • 本文由 发表于 2020年7月26日 02:47:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/63092228.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定