Java CodeHS广告牌AP CS A级
我正在与CodeHS Java问题公告牌前10名做斗争。我正在尝试引用top10 ArrayList中的音乐家对象,但我不断得到错误: 无法从静态上下文引用非静态变量top10 以下是我对这一部分的代码:Java CodeHS广告牌AP CS A级,java,object,arraylist,methods,Java,Object,Arraylist,Methods,我正在与CodeHS Java问题公告牌前10名做斗争。我正在尝试引用top10 ArrayList中的音乐家对象,但我不断得到错误: 无法从静态上下文引用非静态变量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
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.");
}
}
公共作废添加(m){
//如果列表中的音乐家少于10位,并且音乐家拥有白金唱片的地位,则将音乐家添加到前10位阵列列表中
如果(m.getIsPlatinum(m.getAlbumsSold())和&top10.size()为什么首先要替换static?
不能在一个非静态的函数中引用非静态的变量。因此,只需将替换函数设置为非静态。Musitor是一个对象,而不是一个类。静态属于一个类。从替换()中删除静态变量,使其读作public void replace(Musitor replace)
鉴于您提供的代码,无法判断您是否从静态上下文调用该方法