我正在尝试使用 Comparable 函数 compareTo 两个街道地址。我目前正在处理地址的字符串(街道名称)。到目前为止,我有以下代码。我最终也希望能够比较街道号码,但我希望能够先修复此代码。每当我尝试编译此代码时,都会收到以下错误:
StreetAddress.java:45: error: constructor StreetAddress in class StreetAddress cannot be applied to given types;
StreetAddress add1 = new StreetAddress("cartesian road");
^
required: no arguments
found: String
reason: actual and formal argument lists differ in length
StreetAddress.java:46: error: constructor StreetAddress in class StreetAddress cannot be applied to given types;
StreetAddress add2 = new StreetAddress("cartesian road");
^
required: no arguments
found: String
reason: actual and formal argument lists differ in length
StreetAddress.java:47: error: constructor StreetAddress in class StreetAddress cannot be applied to given types;
StreetAddress add3 = new StreetAddress("n kings street");
^
required: no arguments
found: String
reason: actual and formal argument lists differ in length
StreetAddress.java:48: error: constructor StreetAddress in class StreetAddress cannot be applied to given types;
StreetAddress add4 = new StreetAddress("pioneer parkway");
^
required: no arguments
found: String
reason: actual and formal argument lists differ in length
StreetAddress.java:49: error: constructor StreetAddress in class StreetAddress cannot be applied to given types;
StreetAddress add5 = new StreetAddress("starry avenue");
^
required: no arguments
found: String
reason: actual and formal argument lists differ in length
5 errors
public class StreetAddress implements Comparable<StreetAddress>
{
protected int num;
protected String stName;
public void StreetAddress(int n, String s){
num = n;
stName = s;
}
public int getNum(){
// returns the street number
return num;
}
public String getName(){
// returns the street name
return stName;
}
public int compareTo(StreetAddress street) throws ClassCastException{
// exception prevents crash if an address is not compared to
// another address
StreetAddress x = (StreetAddress) street;
int compareName = this.stName.compareTo(street.stName);
if (compareName < 0){
// first address comes after compared address
System.out.println("test<0");
}
else if (compareName == 0){
// same address
System.out.println("test equal");
}
else{
// first address comes before compared address
System.out.println("test > 0");
}
}
public static void main(String args[])
{
StreetAddress add1 = new StreetAddress("cartesian road");
StreetAddress add2 = new StreetAddress("cartesian road");
StreetAddress add3 = new StreetAddress("n kings street");
StreetAddress add4 = new StreetAddress("pioneer parkway");
StreetAddress add5 = new StreetAddress("starry avenue");
add1.compareTo(add2);
add4.compareTo(add1);
add3.compareTo(add3);
add2.compareTo(add5);
}
}