0

我将一个字符串传递给一个以逗号作为分隔符的方法。

"TMJ,Emma,Sarah"

我使用“,”作为要拆分的正则表达式来标记这个字符串。

然后,我迭代标记化数组的长度,将每个元素与所有可能值的 HashMap 进行比较。如果正在测试的值是 HashMap 中的一个键,那么我将获取该键的值并将其存储在另一个字符串中。

我想将键的每个值附加到保存值的字符串中。

它似乎只迭代一次,然后跳出循环并仅返回它在哈希图中找到的第一件事。

谁能解释为什么?在此先感谢马特。

public static String getrecipientIntergerValues(String recipient) {

        Log.e(TAG, "recipient string list passed in to app obj = " + recipient);


         String[] tokenizedRecipient = recipient.split(",");
         String recipientAsInteger = "";

         for(int i = 0; i < tokenizedRecipient.length; i++){
             Log.e(TAG, "tokenizedRecipient = " + tokenizedRecipient[i].toString());
         }

         Log.e(TAG, "tokenizedRecipient length = " + tokenizedRecipient.length);

         for(int i = 0; i < tokenizedRecipient.length; i++){



             if(recipients.containsKey(tokenizedRecipient[i].toString())){
                 Log.e(TAG, "hashmap contains key " + tokenizedRecipient[i].toString() + "with value " + recipients.get(tokenizedRecipient[i].toString()));
                 String integerValueOfName = recipients.get(tokenizedRecipient[i].toString());
                 recipientAsInteger = recipientAsInteger + integerValueOfName + ",";

             }

         }

        Log.e(TAG, "recipient list as integers = " + recipientAsInteger);

        return recipientAsInteger;
    }

.

09-20 16:33:51.039: E/NfcScannerApplication(25835): recipient string list passed in to app obj = Emma, TMJ, 
09-20 16:33:51.039: E/NfcScannerApplication(25835): tokenizedRecipient = Emma
09-20 16:33:51.064: E/NfcScannerApplication(25835): tokenizedRecipient =  TMJ
09-20 16:33:51.064: E/NfcScannerApplication(25835): tokenizedRecipient =  
09-20 16:33:51.079: E/NfcScannerApplication(25835): tokenizedRecipient length = 3
09-20 16:33:51.079: E/NfcScannerApplication(25835): hashmap contains key Emmawith value 3
09-20 16:33:51.089: E/NfcScannerApplication(25835): recipient list as integers = 3,
4

3 回答 3

1

您的日志记录表明您传递的字符串"Emma, TMJ, "不是您建议的。

09-20 16:33:51.039: ... recipient string list passed in to app obj = Emma, TMJ, 

我相信解决您的问题的方法是使用String.split(",",0),因为这将在最后删除空字符串。您可能还希望String.trim()在您的地图中查找字符串之前使用。

于 2013-09-20T15:47:55.457 回答
0

在没有看到recipients包含的内容的情况下,您可以放心地假设

if(recipients.containsKey(tokenizedRecipient[i].toString())){
    Log.e(TAG, "hashmap contains key " + tokenizedRecipient[i].toString() + "with value " + recipients.get(tokenizedRecipient[i].toString()));
    String integerValueOfName = recipients.get(tokenizedRecipient[i].toString());
    recipientAsInteger = recipientAsInteger + integerValueOfName + ",";
}

只执行一次,因为recipients只包含Emma. for循环循环 3 次,但只匹配一次if

如果您的recipients地图包含键EmmaTMJ那么您的问题就是您的split()方法,请查看其他答案。

于 2013-09-20T15:41:48.940 回答
0

如果输入字符串是,"Emma, TMJ,"那么split将返回一个包含这两个字符串的数组:

"Emma"
" TMJ"

最后一个将不匹配"TMJ"。尝试使用", *"(或者,更好,"\\s*,\\s*")作为正则表达式来使用split(这会将多余的空格视为分隔符的一部分,而不是将它们包含在结果字符串中);或.trim()在结果字符串上使用该方法(删除前导和尾随空格)。

于 2013-09-20T15:52:36.457 回答