语法错误,告诉我它想要;和其他几件事

时间:2014-04-06 14:09:53

标签: java eclipse

试图通过一些代码来完成我正在做的任务。它可能很简单,但对于我的生活,我无法弄清楚为什么我在第一行得到上述错误

(public WaterLog.......). 

后来我想把它传给这一行:

[ log = new WaterLog(8, damCapacity); ]

任何帮助将不胜感激,我很抱歉。

public class WaterLog(Integer windowSize, Integer maxEntry) {

private Integer size = windowSize;
private Integer max = maxEntry;
private ArrayList theLog(int windowSize);
private int counter = 0;


public void addEntry(Integer newEntry) throws SimulationException {

    theLog.add(0, newEntry);
    counter++;

}

public Integer getEntry(Integer index) throws SimulationException {

    If (thelog.isEmpty() || thelog.size() < index) {
        return null;
    }
    return thelog.get(index);

}

public Integer variation() throws SimulationException {

    int old, recent = 0;
    recent = thelog.get(0);
    old = thelog.get(thelog.size-1);
    return recent-old;
}

public Integer numEntries() {

    return counter;

}

}

2 个答案:

答案 0 :(得分:1)

假设SimulationException被正确定义:

class WaterLog{

private Integer size;
private Integer max ;
private ArrayList<Integer> theLog; //parameterize your lists
private int counter = 0;

public WaterLog(Integer windowSize, Integer maxEntry) //this is the behavior you were    looking for
{
this.size = windowSize;
this.max = maxEntry;
theLog = new ArrayList<Integer>(windowSize);
}

public void addEntry(Integer newEntry) throws SimulationException {

theLog.add(0, newEntry);
counter++;

}

public Integer getEntry(Integer index) throws SimulationException {

if (theLog.isEmpty() || theLog.size() < index) { //Java is case sensitive
    return null;
}
return theLog.get(index);

}

public Integer variation() throws SimulationException {

int old, recent = 0;
recent = theLog.get(0);
old = theLog.get(theLog.size()-1); //again, watch case, also size is a method
return recent-old;
}

public Integer numEntries() {

return counter;

}

}

查看我添加的评论。

编辑:为了进一步解释发生了什么,让我们来看看你在做什么。

public class WaterLog(Integer windowSize, Integer maxEntry) {

private Integer size = windowSize;
private Integer max = maxEntry;
private ArrayList theLog(int windowSize);
private int counter = 0;

您似乎将类与构造函数混淆了。您定义的变量是属性,这是正确的。您需要使用我在答案中显示的语法来创建构造函数。出于同样的原因,您无法访问windowSize等变量。为了解决这个问题,我们允许它们仍然在构造函数之外定义,但在其中分配值,我们可以访问windowSize和{{1} }。

答案 1 :(得分:0)

如果要将某些参数传递给此类,则需要构造函数。默认情况下,每个类和每个类都带有一个默认构造函数 - 就在那里,你只是看不到它(但可以声明它)。你可以做的是制作一个重载的construcotr(需要一些参数),这就是你想要的......

如果你有一个班级

class WaterLog {
    // no constructor
}

上面真的是

class WaterLog {
   public WaterLog() {
      // this is the constructor - if you do not declare it its still here, you just dont see it. Ofcourse you have option to declare it.
   }
}

重载的构造函数就是这样的

class WaterLog {
   public WaterLog() {
     //default constructor
   }
   public WaterLog(Integer int, String string, etc...) {
     //overloaded constructor
   }
}

以上是将参数传递给此类构造函数所需的内容。我不善于解释事情,但如果你需要更多澄清,请告诉我:)