【问题标题】:Android: Compare words based on position and using spannableAndroid:根据位置比较单词并使用spannable
【发布时间】:2015-03-15 18:58:40
【问题描述】:

我这里有一个代码可以改变句子中单词的颜色。如果找到的单词位于相同的位置,则为紫色。如果答案包含一个单词但位置不同,则为黄色;如果未找到该单词,则为红色。

我现在的问题是即使单词的位置不同,颜色也会变成紫色。我还尝试使用 splitInput[i].contains(splitAnswer[i]) 将单词更改为黄色,但我得到了重复的单词,例如“It was a sample sample sentence sentence”。

        String answer = "This is a sample sentence"
        String userInput = "It was a sample sentence"
        boolean wordFound = false;
        String[] splitAnswer = answer.split(" ");
        String[] splitInput = userInput.split(" ");

        for (int i=0; i<splitAnswer.length;i++) 
        {
            for (int j=0;j<splitInput.length;j++) 
            {
                if(splitInput[i].equalsIgnoreCase(splitAnswer[i])) 
                {
                wordFound = true;
                //color the word to violet
                }
            {
            if(wordFound==false)
            {
            //color the word to red 
            }
             //display the sentence
             wordFound == false; 
        }

【问题讨论】:

    标签: android arrays for-loop contains spannable


    【解决方案1】:
    String answer = "This is a sample sentence";
            String userInput = "It was a sample sentence";
            boolean wordFound = false;
            String[] splitAnswer = answer.split(" ");
            String[] splitInput = userInput.split(" ");
    
             for (int i=0; i<splitAnswer.length;i++) 
             {
    
            if (splitInput[i].equalsIgnoreCase(splitAnswer[i]))
            {
    
                System.out.println ("Word found");
            }
            else if(!wordFound)
            {
    
                System.out.println ("Word Not found");
            }
        }
    

    【讨论】:

    • 您好!抱歉回复晚了。我上次尝试了该代码,但收到了空指针异常错误消息。顺便说一句,userInput 不是恒定的,数组长度可能会根据用户输入而改变。你能帮我解决这个问题吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-18
    • 1970-01-01
    • 1970-01-01
    • 2022-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多