![](/img/trans.png)
[英]How to access String within an ArrayList within an ArrayList within a HashMap?
[英]How to access an array when it is within an arraylist?
我要執行的總體目標是將字符串與數組的索引0(保存在arraylist中)進行比較,如果字符串相同(忽略大小寫),則調用匹配大小寫的方法字符串到翻譯后單詞的距離(保存在arraylist內數組的索引1處)。 當我運行此代碼並打印出翻譯后的arraylist的內容時,我得到了所有“不匹配”字符。 我假設這是因為我沒有以正確的方式訪問所需的索引。 請幫忙!
public static String translate(String word, ArrayList<String[]> wordList) {
if (word == "." || word == "!" || word == ";" || word == ":") {
return word;
}
for (int i = 0; i < wordList.size(); i++) {
String origWord = wordList.get(i)[0];
String transWord = wordList.get(i)[1];
if (word.equalsIgnoreCase(origWord)) { //FIXME may need to change if you need to switch from translated to original
String translated = matchCase(word, transWord);
return translated;
}
}
String noMatch = Character.toString(Config.LINE_CHAR);
return noMatch;
}
樣本數據和預期結果
字=“你好”
wordList.get(i)[0] =“你好”
wordList.get(i)[1] =“霍拉”
(word和wordList.get(i)[0]匹配,因此執行下一步)
區分大小寫方法被調用,並以與原始單詞相同的大小寫返回翻譯后的單詞->
翻譯=“霍拉”
返回翻譯的單詞。
(for循環遍歷整個wordList,直到找到匹配項,然后調用translate方法)
**
區分大小寫的代碼
public static String matchCase(String template, String original) {
String matched = "";
if (template.length() > original.length()) {
for (int i = 1; i <= original.length(); i++) {
if (template.charAt(i-1) >= 'a' && template.charAt(i-1) <= 'z') {
if (i == original.length()) {
matched += original.substring(original.length() - 1).toLowerCase();
}
else {
matched += original.substring((i-1), i).toLowerCase();
}
}
else if (template.charAt(i-1) >= 'A' && template.charAt(i-1) <= 'Z') {
if (i == original.length()) {
matched += original.substring(original.length() - 1).toUpperCase();
}
else {
matched += original.substring((i-1), i).toUpperCase();
}
}
}
return matched;
}
else if (template.length() < original.length()) {
int o;
original.toLowerCase();
for (int i = 1; i <= template.length(); i++) {
if (template.charAt(i-1) >= 'a' && template.charAt(i-1) <= 'z') {
if (i == template.length()) {
matched += original.substring(original.length() - 1).toLowerCase();
}
else {
matched += original.substring((i-1), i).toLowerCase();
}
}
else if (template.charAt(i-1) >= 'A' && template.charAt(i-1) <= 'Z') {
if (i == template.length()) {
matched += original.substring(original.length() - 1).toUpperCase();
}
else {
matched += original.substring((i-1), i).toUpperCase();
}
}
String newMatched = matched + original.substring(i, original.length() - 1);
matched = newMatched;
newMatched = "";
}
return matched;
}
return original;
}
我已經測試了您的代碼,並且可以很好地與您提供的示例一起使用。 對於您的錯誤,我無能為力。
但是,有一些錯誤需要通知,並提出一些改進建議:
matchCase
失敗。 ==
進行比較。 使用equals
方法並查看原因 。 這不是很重要,但是為什么總是要計算noMatch
。 為什么不一次將其聲明為常數?
public static final String NO_MATCH = String.valueOf(Config.LINE_CHAR);
更重要的是,我認為matchCase
與設計matchCase
,而且過於復雜。 我認為您應該確定要翻譯的單詞是全部小寫還是大寫,或者首字母大寫,隨后的字母小寫。 當長度不同時,您所做的操作(逐個字母比較情況)並不重要。
charAt
而不是substring
會更簡單,更快捷。 Map
來進行翻譯查找? ...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.