繁体   English   中英

如何在java中定义一个字符串数组并在switch case中使用它

[英]How to define a string array in java and use it in switch case

嗨亲爱的朋友们,我想在 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;
}

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

尝试枚举数组中所有不同的可能字符串通常是一个坏主意,而不是编写程序的正确方法。 确定您的示例有效,但是如果您的可能字符串集不只是 {'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)
    }
}

我会这样做:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM