【问题标题】:How to define a string array in java and use it in switch case如何在java中定义一个字符串数组并在switch case中使用它
【发布时间】:2015-11-05 07:58:10
【问题描述】:

亲爱的朋友,我想在java中定义一个String数组并使用每个 java中switch-case中该数组的单元格以计算每个字符串 元素。例如,你能帮我解决它吗?谢谢。

int i=20;
String [] str =new String[i];
string[0]="This";
string[1]="is";
string[2]="a";
string[3]="Test";
string[4]="This";
string[5]="This";
string[6]="a";
string[7]="a";
string[8]="a";
string[20]="Test";
switch(i)
{
case(0):this++
break;
case(1):is++
break;
case(2):a++
break;
case(3):test++
break;
}

【问题讨论】:

  • 您不想使用 Hashmap 的任何特殊原因,然后为所有输入单词递增字符串的 int?
  • 你认为this++ 会做什么?
  • 请熟悉Java 语言的基础知识,特别是它的语法和保留字。 this++ 很可能不是你想的那样!

标签: java arrays string


【解决方案1】:

尝试枚举数组中所有不同的可能字符串通常是个坏主意,也不是编写程序的正确方法。当然,您的示例有效,但是如果您的一组可能的字符串不只是 {'this', 'is', 'a', 'test'},而是说 10000 个元素,会发生什么?如果您不确切知道数组中的String 元素怎么办?正如之前的用户所提到的,您想使用HashMap<String, Integer>

String[] arr = yourStringArray; //wherever your Strings are coming from
Map<String, Integer> strCounts = new HashMap<String, Integer>; //this stores the strings you find
for (int i = 0; i < arr.length; i++) {
    String str = arr[i];
    if (strCounts.containsKey(str)) {
        strCounts.get(str) += 1; //if you've already seen the String before, increment count
    } else {
        strCounts.put(str, 1); //otherwise, add the String to the HashMap, along with a count (1)
    }
}

【讨论】:

    【解决方案2】:

    虽然我不太明白您要做什么,但这是我的两分钱。您可能会收到ArrayIndexOutOfBoundsException。这是因为当您创建一个大小为20 的数组时,它可以恰好容纳 20 个项目。从范围019。所以尝试做string[20]="Test"; 会报错,因为它越界了。

    【讨论】:

      【解决方案3】:

      我会这样做:

      int count;
      String currentWord;
      Map<String, Integer> wordMap = new HashMap<>();
      StringTokenizer tokenizer = new StringTokenizer(mySentence);
      while(tokenizer.hasNext()){
      count = null;
      currentWord = tokenizer.nextToken();
      count = wordMap.get(currentWord);
      if(count == null) wordMap.put(currentWord, 1);
      else wordMap.put(currentWord, ++count);
      }
      

      【讨论】:

        猜你喜欢
        • 2012-05-01
        • 2019-08-10
        • 2013-08-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多