我正在尝试使用我创建的类(class),但是当我调用该类(class)时它不起作用,我有点迷路了。
错误出在程序底部的类调用和tally的初始化处。
package counter;
public class Counter {
private int value;
public Counter(int intialValue){
value = intialValue;
}
private void count() {
value = value + 1;
}
private void reset(){
value = 0;
}
public int getValue(){
return value;
}
Counter tally = new Counter();
tally.count();
}
最佳答案
所有 Java 语句都必须放入某种方法中。
目前您的最后两行不在方法中。
Counter tally = new Counter();
tally.count();
尝试这样的事情:
public class Counter {
... existing members ...
public static void main(String[] args) {
int initialValue = Integer.parseInt(args[0]);
Counter tally = new Counter(initialValue);
tally.count();
}
}
关于java - 在 Java 中使用类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14651242/