【发布时间】:2017-03-15 12:32:11
【问题描述】:
我正在尝试创建一个 getCounter() 方法,每次调用 getCounter() 方法时都会向上计数。例如,如果该方法被调用 10 次,则输出应为:1,2,3...10。
这是我拥有的当前代码: 主类:
public class JavaLab5 {
public static final int DEBUG = 0;
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Student s[] = new Student[10];
s[0] = new MathStudent("Smith");
s[1] = new MathStudent("Jack");
s[2] = new MathStudent("Victor");
s[3] = new MathStudent("Mike");
s[4] = new ScienceStudent("Dave");
s[5] = new ScienceStudent("Oscar");
s[6] = new ScienceStudent("Peter");
s[7] = new ComputerStudent("Philip");
s[8] = new ComputerStudent("Shaun");
s[9] = new ComputerStudent("Scott");
for (int loop = 0; loop < 10; loop++) {
System.out.print(loop);
System.out.println(s[loop].getSubjects());
}
}
}
学生班:
public class Student {
String name;
int count
public static int instances = 0;
//Getters
public String getName() {
return this.name;
}
// Setters
public void setName(String name) {
if (JavaLab5.DEBUG > 3) System.out.println("In Student.setName. Name = "+ name);
this.name = name;
}
/**
* Default constructor. Populates name,age and gender
* with defaults
*/
public Student() {
instances++;
this.name = "Not Set";
}
/**
* Constructor with parameters
* @param name String with the name
*/
public Student(String name) {
this.name = name;
}
/**
* Destructor
* @throws Throwable
*/
protected void finalize() throws Throwable {
//do finalization here
instances--;
super.finalize(); //not necessary if extending Object.
}
public void getCounter() {
for (int x = 0; x < 10; x++) {
count++;
System.out.println(count);
}
}
public String toString () {
return this.name;
}
public String getSubjects() {
return this.getSubjects();
}
}
我的问题是如何实现这样的方法来从我的 Main 类中调用它。
【问题讨论】:
-
有什么问题?
-
@YounesM 想在每次调用 getCounter() 方法时创建一个向上计数的计数器。
-
@anon1234 这是对您想要做的事情的描述,而不是问题。请提出问题。
-
我投票结束,因为我仍然不清楚你在问什么。
-
@domdom 不清楚我在问什么,但您设法为我提供了答案,然后现在将其删除,并且所有这些用户都设法给了我答案。