gpt4 book ai didi

Java - StringBuilder 替换()显示错误 : method String. 替换(char,char)不适用

转载 作者:行者123 更新时间:2023-12-01 18:00:56 26 4
gpt4 key购买 nike

我正在尝试编译和测试我在网上看到的代码 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)

我检查了代码的替换方法,它显示了正确的数据类型,即(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();
}

}

最佳答案

试试这个:

StringBuilder address = new StringBuilder(sc.nextLine());

关于Java - StringBuilder 替换()显示错误 : method String. 替换(char,char)不适用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40967133/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com