简体   繁体   中英

How to Sum String double Value

I have a string like 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 .

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.

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"; 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. Instead define a double variable for the number of km: double km = 10.1 and a String variable for "km". Then (when you want to get It as an String) redefine the variable for km with the answer of the operation.

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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