简体   繁体   English

如何对字符串双值求和

[英]How to Sum String double Value

I have a string like 24.5 km10.1 km30.9 km .我有一个像24.5 km10.1 km30.9 km这样的字符串。

I want to compute the sum of all the distances in the string but I'm not able to do it.我想计算字符串中所有距离的总和,但我无法做到。 I'm getting a NumberFormatException .我收到NumberFormatException

Here is my code这是我的代码

String stringValue = getDistanceOnRoad(lat, long, lat2, long2);
double sumValue = 0.0;

Log.d("my string is", stringValue);
try {
    sumValue = Double.parseDouble(stringValue);
    Log.d("distance there plus", String.valueOf(sumValue));
} catch (NumberFormatException e){
    System.out.println("not a number");
}

I'm getting the distance from this method, everything is working fine but I'm not able to compute the sum of all distances.我正在从这种方法中获得距离,一切正常,但我无法计算所有距离的总和。

How to calculate distance between two locations using their longitude and latitude value 如何使用经度和纬度值计算两个位置之间的距离

private String getDistanceOnRoad(double latitude, double longitude,
        double prelatitute, double prelongitude) {
    String result_in_kms = "";
    String url = "http://maps.google.com/maps/api/directions/xml?origin="
            + latitude + "," + longitude + "&destination=" + prelatitute
            + "," + prelongitude + "&sensor=false&units=metric";
    String tag[] = { "text" };
    HttpResponse response = null;
    try {
        HttpClient httpClient = new DefaultHttpClient();
        HttpContext localContext = new BasicHttpContext();
        HttpPost httpPost = new HttpPost(url);
        response = httpClient.execute(httpPost, localContext);
        InputStream is = response.getEntity().getContent();
        DocumentBuilder builder = DocumentBuilderFactory.newInstance()
                .newDocumentBuilder();
        Document doc = builder.parse(is);
        if (doc != null) {
            NodeList nl;
            ArrayList args = new ArrayList();
            for (String s : tag) {
                nl = doc.getElementsByTagName(s);
                if (nl.getLength() > 0) {
                    Node node = nl.item(nl.getLength() - 1);
                    args.add(node.getTextContent());
                } else {
                    args.add(" - ");
                }
            }
            result_in_kms = String.format("%s", args.get(0));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result_in_kms;
}

If your string is like 24.5 km10.1 km30.9 km, then before converting it to double you should parse the string.如果您的字符串类似于 24.5 km10.1 km30.9 km,那么在将其转换为 double 之前,您应该解析该字符串。

String stringValue = getDistanceOnRoad(lat, long, lat2, long2);
double sumValue = 0.0;

Log.d("my string is", stringValue);
try {
  String[] distances = stringValue.split(" km");
  for (String distance: distances) {
    sumValue = sumValue + Double.parseDouble(distance);
  }
  Log.d("distance there plus", String.valueOf(sumValue));
} catch (NumberFormatException e) {
  System.out.println("not a number");
}

Okay, the problem there is that you're trying to parse String S = "10.1 km";好的,问题在于您正在尝试解析String S = "10.1 km"; to a double variable.到双变量。 However, the "km" part of the String isn't a number, so the java compiler isn't able to parse it.但是,字符串的“km”部分不是数字,因此 java 编译器无法解析它。 Instead define a double variable for the number of km: double km = 10.1 and a String variable for "km".而是为公里数定义一个双变量: double km = 10.1和一个字符串变量用于“km”。 Then (when you want to get It as an String) redefine the variable for km with the answer of the operation.然后(当您想将它作为字符串获取时)使用操作的答案重新定义 km 的变量。

Try this试试这个

String test = "24.5 km10.1 km30.9 km";
String[] parsedString = test.split("(km)");
double sum = 0;
for(String s : parsedString) {
    sum += Double.parseDouble(s.trim());
}

try this试试这个

String s = "24.5 km10.1 km30.9 km";

String[] items = s.split("km");
double result = 0;

for (int i = 0 ; i < items.length ; i++) {   
    result = result + Double.parseDouble(items[i]); 
}

System.out.print("result = " + result);

You should split by km, then sum the values, here is the method :您应该按公里分割,然后对值求和,这是方法:

private static double parseAndSum(String string) {

    double sumValue = 0.0;
    String[] nums = string.split("km");

    int i=0;
    for(i=0;i<nums.length;i++) {
        sumValue += Double.parseDouble(nums[i].trim());
    }
    return sumValue;
}

And here how you call it :在这里你如何称呼它:

String string = getDistanceOnRoad(latitude, longitude, prelatitute, prelongitude);    
double result = parseAndSum(string);
System.out.println("Total is : " + result + "km");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM