简体   繁体   English

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

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

Hi dear friends, I want to define a String array in java and use every cells of that array in switch-case in java to count every string elements.for example can you you help me to fix it thanks.嗨亲爱的朋友们,我想在 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;
}

While i don't really understand what you are trying to do, here are my two cents.虽然我真的不明白你想要做什么,但这是我的两分钱。 You are probably getting an ArrayIndexOutOfBoundsException .您可能会收到ArrayIndexOutOfBoundsException This is because when you create an array of size 20 , it can hold exactly 20 items.这是因为当您创建一个大小为20的数组时,它可以正好容纳 20 个项目。 From range 0 to 19 .从范围019 So trying to do string[20]="Test";所以尝试做string[20]="Test"; will give an error because it's out of bounds.会报错,因为它越界了。

Trying to enumerate all the different possible strings in the array is generally a bad idea and not the correct way to write your program.尝试枚举数组中所有不同的可能字符串通常是一个坏主意,而不是编写程序的正确方法。 Sure your example works, but what would happen if your set of possible strings was not just {'this', 'is', 'a', 'test'}, but instead had say 10000 elements?确定您的示例有效,但是如果您的可能字符串集不只是 {'this', 'is', 'a', 'test'} 而是说 10000 个元素会发生什么? What if you didn't know exactly what String elements were in the array?如果您不确切知道数组中的String元素怎么办? As a previous user mentioned, you want to use a HashMap<String, Integer> .正如之前的用户提到的,您想使用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)
    }
}

I would do it this way:我会这样做:

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