字符串数组列表到文本视图以显示它

时间:2018-02-11 19:41:01

标签: java arrays list

如何将此数组列表字符串添加到文本视图中,以便我可以在tts上使用它?试过很多代码,但没有真正起作用,我对android studio来说真的很新,所以我听起来真的很新。 下面是我的数组列表代码!

private String getEmotion(RecognizeResult res) {
    List<Double> list = new ArrayList<>();
    Scores scores = res.scores;

    list.add(scores.anger);
    list.add(scores.happiness);
    list.add(scores.contempt);
    list.add(scores.disgust);
    list.add(scores.sadness);
    list.add(scores.neutral);
    list.add(scores.surprise);
    list.add(scores.fear);

    //sort list
    Collections.sort(list);

    double maxNum = list.get(list.size()  -1);

    if(maxNum == scores.anger)
        return "Anger";
    else if(maxNum == scores.happiness)
        return "Happiness";
    else if(maxNum == scores.contempt)
        return "Contempt";
    else if(maxNum == scores.disgust)
       return "Disgust";
    else if(maxNum == scores.sadness)
        return "Sadness";
    else if(maxNum == scores.neutral)
        return"Neutral";
    else if(maxNum == scores.surprise)
        return "Surprise";
    else if(maxNum == scores.fear)
        return "Fear";
    else
        return "Can't Detect";
}

1 个答案:

答案 0 :(得分:0)

我认为你的问题是不正确的双值比较:double == double在一般情况下不能正常工作;比较double的正确方法是Double.compare(double, double) == 0

如果您将maxNum == scores.anger等所有操作替换为Double.compare(maxNum, scores.anger) == 0,我认为您的代码可以正常运行。

此外,我可以为您提供如何简化此代码的方法之一:

private static final class Data {
    double maxNum = Double.MIN_VALUE;
    String emotion = "Can't Detect";

    void applyMax(double score, String emotion) {
        if (Double.compare(score, maxNum) > 0) {
            maxNum = score;
            this.emotion = emotion;
        }
    }
}

private String getEmotion(RecognizeResult res) {
    Scores scores = res.scores;
    Data data = new Data();

    data.applyMax(scores.anger, "Anger");
    data.applyMax(scores.happiness, "Happiness");
    data.applyMax(scores.contempt, "Contempt");
    data.applyMax(scores.disgust, "Disgust");
    data.applyMax(scores.sadness, "Sadness");
    data.applyMax(scores.neutral, "Neutral");
    data.applyMax(scores.surprise, "Surprise");
    data.applyMax(scores.fear, "Fear");

    return data.emotion;
}