【问题标题】:Switch Variables Depending on If Statement根据 If 语句切换变量
【发布时间】: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


【解决方案1】:

您的代码没有任何问题。

你可以随便改一下:

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
} 

【讨论】:

    【解决方案2】:

    您可以使用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));
    

    【讨论】:

    • 我会试试的。我刚接触Java,所以没有学过HashMaps之类的东西,但是我知道要改成小写,我忘记了如何正确使用它。
    【解决方案3】:

    你有,一行打印

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

    考虑到您的comment,您可以将最后两行更改为:

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

    【讨论】:

      猜你喜欢
      • 2020-07-22
      • 1970-01-01
      • 2017-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-23
      • 2021-03-20
      • 1970-01-01
      相关资源
      最近更新 更多