簡體   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