【问题标题】:CodeHS Billboard Class AP CS ACodeHS 广告牌类 AP CS A
【发布时间】:2020-03-23 08:25:36
【问题描述】:

我正在努力解决 CodeHS Java 问题 Billboard Top 10。我试图在 top10 ArrayList 中引用一个 Musician 对象,但我不断收到错误消息:

不能从静态上下文中引用非静态变量 top10。

这是我为这个部分准备的代码:

public void add(Musician m) {
    //if less than 10 musicians on the list and musician has platinum status, add musician to top10 array list
    if(m.getIsPlatinum(m.getAlbumsSold())&&top10.size()<10) {
        top10.add(m);
    }
    //if already 10 musicians (and platinum), call replace method
    else if(m.getIsPlatinum(m.getAlbumsSold())&&top10.size()==10) {
        replace(m);
    }
    // else print musician couldn't be added to top10 list
    else System.out.println("The musician could not be added to the top10 list.");
}

public static void replace(Musician replacer) {
    //if lowest # weeks on top40 is lower than # weeks of new musician: replace old
    Musician temp = top10.get(0);
    int lowest40Weeks = temp.getWeeksInTop40();
    int lowestIndex = 0;
    for(int i = 0; i<top10.size(); i++) {
        temp = top10.get(i);
        if(temp.getWeeksInTop40()<lowest40Weeks) {
            lowest40Weeks = temp.getWeeksInTop40();
            lowestIndex = i;
        }
    }
    if(lowest40weeks<replacer.getWeeksInTop40()) {
        top10.set(lowestIndex, replacer);
        System.out.println(replacer.getName() + " has replaced " + top10.get(lowestIndex).getName() + " on the top 10 list.");
    }
    //print message to user about replacement
    //else print musician can't be added because not enough weeks on top40
    else {
        System.out.println(replacer.getName() + " could not be added to the top 10 list because they do not have enough weeks in the top 40.");
    }
}

当我在方法中引用 top10 时,我的所有问题都在 replace 方法中。 任何帮助将不胜感激!

【问题讨论】:

  • 音乐家是一个对象,而不是一个类。静态属于一个类。从您的 replace() 中删除静态,使其显示为 public void replace(Musician replacer)
  • 根据您提供的代码,您是否从静态上下文中调用该方法无法确定

标签: java object arraylist methods


【解决方案1】:

为什么首先要替换静态? 您不能在函数中引用不是静态的变量。所以只要让替换函数不是静态的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多