[英]Writing a method to calculate length/average
我試圖用我的主要組件所需的所有方法編寫一個類,但在弄清楚如何使用這些方法確定所需的值時遇到了麻煩。 我遇到麻煩的是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;
}
}
對於getCount
,創建一個static int
,每個構造函數都將其遞增。
對於getAverageLength
,使用每個構造函數添加到的行數之和制成一個static int
,然后將其除以計數。
代碼有幾個問題。 首先,建議記錄在注釋中應該使用的方法。 這將對您和其他人有所幫助。 其次,這些方法:
public void setLength(int i) {
getLength = getLength();
}
getLength
私有成員變量可能命名錯誤。 我懷疑這個意圖是一個像length
這樣的名詞,而getLength()
是一種旨在返回當前length
。 此方法采用原始int
數據類型來設置double
類型。 這是故意的嗎? 看起來像是一個誤解。 而且,它沒有任何功能,因為它只是將getLength
(再次應為length
)變量設置為方法getLength()
的返回值,該方法又返回getLength
的值。 這是一個補救邏輯和基本數學問題:A = 1 = getLength()= A = 1
public static int getCount() {
return 0;
}
為什么期望從該方法返回除零以外的任何東西?
public static int getAverageLength(){
return 0;
}
同樣在這里...基本邏輯問題。
我不會在論壇上發布此類問題,因為它在提出問題之前缺乏基本的功課。
建立一個HashMap<MyLine, Integer>
整數是MyLine的長度。
您只需將要計算的MyLine
對象放入該地圖即可。
{ml1:0, ml2:10, ml3:7}
那么您就可以計算出所需的一切。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.