我正在尝试编译和测试我在网上看到Expanding an IP add的代码。但是,当我尝试编译它时,我收到有关StringBuilder替换方法的错误。它说:
IPadd.java:52: error: no suitable method found for replace(int,int,String)
address.replace(tempCompressLocation,tempCompressLocation+2,":");
^
method String.replace(char,char) is not applicable
(actual and formal argument lists differ in length)
我检查了代码的replace方法,它显示了正确的数据类型,即(int,int,String)。我想知道如何运行这个程序。
import java.util.*;
public class IPadd {
public static void main (String[] args){
Scanner sc = new Scanner(System.in);
System.out.print("Input address: ");
String address = sc.nextLine();
// Store the location where you need add zeroes that were removed during uncompression
int tempCompressLocation=address.indexOf("::");
//if address was compressed and zeroes were removed, remove that marker i.e "::"
if(tempCompressLocation!=-1){
address.replace(tempCompressLocation,tempCompressLocation+2,":");
}
//extract rest of the components by splitting them using ":"
String[] addressComponents=address.toString().split(":");
for(int i=0;i<addressComponents.length;i++){
StringBuilder uncompressedComponent=new StringBuilder("");
for(int j=0;j<4-addressComponents[i].length();j++){
//add a padding of the ignored zeroes during compression if required
uncompressedComponent.append("0");
}
uncompressedComponent.append(addressComponents[i]);
//replace the compressed component with the uncompressed one
addressComponents[i]=uncompressedComponent.toString();
}
//Iterate over the uncompressed address components to add the ignored "0000" components depending on position of "::"
ArrayList<String> uncompressedAddressComponents=new ArrayList<String>();
for(int i=0;i<addressComponents.length;i++){
if(i==tempCompressLocation/4){
for(int j=0;j<8-addressComponents.length;j++){
uncompressedAddressComponents.add("0000");
}
}
uncompressedAddressComponents.add(addressComponents[i]);
}
//iterate over the uncomopressed components to append and produce a full address
StringBuilder uncompressedAddress=new StringBuilder("");
Iterator it=uncompressedAddressComponents.iterator();
while (it.hasNext()) {
uncompressedAddress.append(it.next().toString());
uncompressedAddress.append(":");
}
uncompressedAddress.replace(uncompressedAddress.length()-1, uncompressedAddress.length(), "");
return uncompressedAddress.toString();
}
}
答案 0 :(得分:1)
您正尝试在StringBuilder
上使用String
课程中的替换方法。
address.replace(tempCompressLocation, tempCompressLocation + 2, ":");
地址是String
而不是StringBuilder
答案 1 :(得分:1)
试试这个:
StringBuilder address = new StringBuilder(sc.nextLine());
答案 2 :(得分:1)
String.replace
方法需要两个CharSequence
个或两个char
个。我认为你可以使用:
if (tempCompressLocation != -1) {
address.replace("::", ":");
}
看看它是否适用于您的示例。祝你好运!