代碼如下,其中getX()成功有返回結果,getY()卻報異常.
public class AddressUtilDemo {
public static void main(String[] args){
AddressUtil AddressUtil = new AddressUtil();
AddressUtil.setAddress("3454.234,24l.432");
System.out.println(AddressUtil.getX());
System.out.println(AddressUtil.getY());
}
}
class AddressUtil {
private String address;
public AddressUtil(){}
public AddressUtil(String address){
if(address.indexOf(",")>0){
this.address = address;
}
}
public Double getX(){
String string = address.substring(0, address.indexOf(",")) ;
return Double.parseDouble(string);
}
public Double getY(){
String string = address.substring((address.indexOf(",")+1));
return Double.parseDouble(string);
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address.trim();
}
}
試過string.trim()等方法都無效.debug看到的string確實是預期中的數值.
以下是異常信息:
Exception in thread "main" java.lang.NumberFormatException: For input string: "24l.432"
你應該學會調試,看看getY中的string就知道問題了
24l.432
24後們是 L,不是 1
騷年,你main函數裡setAddress的是3454.234,24l.432(24L,是L不是1),所以y是錯的,轉換失敗了,建議編輯器字體用Source Code Pro 還能看的出來