有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在我的JTextField中显示我的getRank

所以我有这个方法(见下文)。假设搜索存储在数组中的输入文件,以查找包含与用户在jtext字段中输入的名称匹配的子字符串(不区分大小写)的所有名称。这种方法可以做到这一点。然而,当它打印名字的时候,它也应该打印它的最佳十年(比如1920年)。我有一个

public int getRank(int decade) {
    int decadeRank = rank[decade];
    return decadeRank;
}

这是十年,所以秩[0]代表1900,秩[1]代表1910

public int bestDecade() {
    int best = rank[0];
    for(int i = 0; i < DECADES; i++)
        if(rank[i] > best)
            best = rank[i];
    return best;
}

它获得了这个名字在某个十年中的最佳排名,比如351。然而,我似乎不知道如何显示排名十年,而不是排名数字。你可以在下面看到,我一直在尝试,但没有奏效。那么,有人知道我如何才能获得排名吗

private void match(String targetSubstring)
{
    displayArea.setText("");
    displayArea.append("FIND RESULTS for: " + targetSubstring);
    displayArea.append("\n");
    displayArea.append("\n Name               Best Decade");
    displayArea.append("\n---------------         ---------------");
    targetSubstring = targetSubstring.toUpperCase();
    for (int i = 0; i < namesArray.length; i++) {
        String theName = namesArray[i].getName();
        if (theName.toUpperCase().contains(targetSubstring))
        {
            int best = namesArray[i].bestDecade(); //this is what I've been trying
            displayArea.append("\n" + namesArray[i].getName() + (namesArray[i].getRank(best)));
            //  displayArea.append(best);
        }
    }
}

共 (1) 个答案

  1. # 1 楼答案

    以此为主要问题:

    I can't seem to figure out how to display the rank decade and not the rank number

    有了这些信息

    rank[0] represents 1900 and rank[1] represents 1910

    并且知道您的函数返回数字190、1910等。因为您返回了rank[best],但稍后使用了返回值getRank(best),所以您应该返回i,或者删除getRank函数并使用返回值

    假设代码的其余部分正常工作

    选项1:

    // Your code, no changes
    public int bestDecade() {
        int best = rank[0];
        for(int i = 0; i < DECADES; i++)
            if(rank[i] > best)
                best = rank[i];
        return best; // Returns 1900, 1910 etc..
    }
    
    // Changes here to show the returned value (1900, 1910 etc.) directly
    int best = namesArray[i].bestDecade(); //this is what I've been trying
    displayArea.append("\n" + namesArray[i].getName() + best);
    

    选项2:

    // Changes here to return "i" 
    public int bestDecade() {
        int best = 0;
        for(int i = 0; i < DECADES; i++)
            if(rank[i] > rank[best])
                best = i;
        return best; // Returns values between [0 .. DECADES)
    }
    
    // No changes here, use returned value, [0 .. DECADES) in 
    int best = namesArray[i].bestDecade(); // You have "i" here, the index of rank
    displayArea.append("\n" + namesArray[i].getName() + namesArray[i].getRank(best)); // Use "i" here, rank[i]