我正在尝试使用我的主要方法所需的所有方法编写一个类,但是在弄清楚如何使用这些方法确定所需值时遇到了麻烦。我遇到的问题是 getAverageLength 和 getCount。
电流输出:
The length of Line 1 is 1.0
The length of Line 2 is 10.0
There are 0 lines and the average length is 0
The length of Line 1 is 1.0
The length of Line 2 is 10.0
The length of Line 3 is 7.0
There are 0 lines and the average length is 0
预期输出:
The length of Line 1 is 1
The length of Line 2 is 10
There are 2 lines and the average length is 5.5
The length of Line 1 is 7
The length of Line 2 is 10
The length of Line 3 is 7
There are 3 lines and the average length is 8.0
这是我正在使用的主要方法的一部分。
public class TestParts {
public static void main(String[] args) {
MyLine ml1 = new MyLine();
MyLine ml2 = new MyLine(10);
System.out.println("The length of Line 1 is " + ml1.getLength());
System.out.println("The length of Line 2 is " + ml2.getLength());
System.out.println("There are " + MyLine.getCount() +
" lines and the average length is " + MyLine.getAverageLength());
MyLine ml3 = new MyLine(7);
ml1.setLength(7);
System.out.println("The length of Line 1 is " + ml1.getLength());
System.out.println("The length of Line 2 is " + ml2.getLength());
System.out.println("The length of Line 3 is " + ml3.getLength());
System.out.println("There are " + MyLine.getCount() +
" lines and the average length is " + MyLine.getAverageLength());
}
}
以下是我为计算值而编写的单独类。
class MyLine {
private double getLength;
MyLine() {
getLength = 1;
}
double getLength() {
return getLength;
}
MyLine(double setLength) {
getLength = setLength;
}
public void setLength(int i) {
getLength = getLength();
}
public static int getCount() {
return 0;
}
public static int getAverageLength() {
return 0;
}
}