这是我当前的代码-
public class TriangleNumGenerator {
int counter;
int sides;
public TriangleNumGenerator(){
sides = 1;
counter = 2
}
public int nextTri(){
sides = sides+counter;
counter = counter+1;
return sides;
}
public void reset(){
counter = 2;
sides = 1;
}
}
Main(){
TriangleNumGenerator ne = new TriangleNumGenerator();
System.out.println(ne.nextTri());
}
该代码应该执行的操作是每当调用nextTri时,它将打印“ 1、3、6、10”,依此类推。
但是,该代码似乎根本无法打印任何内容。如何使此类实际运行?
答案 0 :(得分:4)
需要做一些更新,我已经在评论中添加了
public class TriangleNumGenerator {
int counter;
int sides;
public TriangleNumGenerator(){
sides = 1;
counter = 2; // forgot ; here**
}
public int nextTri(){
sides = sides+counter;
counter = counter+1;
return sides;
}
public void reset(){
counter = 2;
sides = 1;
}
// you forgot main method; it has to be exactly same so that JVM
// can find it
public static void main(String[] args) {
TriangleNumGenerator ne = new TriangleNumGenerator();
System.out.println(ne.nextTri()); // forgot () in nextTri
}
}
这些是语法错误。如果使用任何IDE,则应报告所有这些信息!