我有一個問題,我不能籠罩我的腦海。也許有人可以幫助我。需要在Java中添加兩個對象,包括英尺和英寸
我創建了一個DISTANCE類,其中包含兩個變量FEET & INCHES。我需要爲該類添加一個方法,該方法添加兩個單獨的距離對象,英尺爲&英寸。
這是到目前爲止我的課:
public class Distance {
static int feet; // 0 - infinity
static int inches; // 0 - infinity
public Distance() { // default constructor
this.feet = 0;
this.inches = 0;
}
public Distance(int ft, int in){ // parametarized constructor
this.feet = ft;
this.inches = in;
System.out.println("constructor w/2 ints : " + feet + ", " + inches);
}
public void setDistance(int ft, int in){
setFeet(ft);
setInches(in);
}
public static int getFeet() {
return (feet);
}
public static void setFeet(int feet) {
Distance.feet = feet;
}
public static int getInches() {
return inches;
}
public static void setInches(int inches) {
Distance.inches = inches;
}
public Distance(Distance d){
//Distance total = d;
d.getDistance();
}
private int getDistance() {
int totalInches;
totalInches = (feet * 12) + inches;
return totalInches;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + feet;
result = prime * result + inches;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Distance other = (Distance) obj;
if (feet != other.feet)
return false;
if (inches != other.inches)
return false;
return true;
}
@Override
public String toString() {
return "Distance [feet=" + feet + ", inches=" + inches + "]";
}
}
的方法我想寫需要添加到遠處的物體。這是我到目前爲止已經試過:如果
公衆距離加(距離d){
Distance total;
total = this.getDistance() + d.getDistance();
return total;
}
好的,它出了什麼問題? – qbit 2014-09-12 20:02:20
我建議在內部只使用英寸。 – Fildor 2014-09-12 20:05:44
以英寸爲單位執行算術運算,然後轉換回英尺和英寸。 – 2014-09-12 20:12:31