Pape Traore
Pape Traore

Reputation: 83

Parsing double value from String in Java

I am supposed to extract the double values from the following string:

r ( 4.5, 1.0 ) 10.5 7 ;  

However my code deletes everything but the digits and that's not what I want. My code:

import java.io.File;
import java.util.Scanner;


public class mine {

    public static void main(String[] args) throws Exception
    {

      String str;
      String numbers;

      Scanner SC=new Scanner(System.in);

      System.out.print("Enter string that contains numbers: ");
      str=SC.nextLine();

      //extracting string
      numbers=str.replaceAll("[^0-9]", "");

      System.out.println("Numbers are: " + numbers);
    }
}

Output of my code:

Enter string that contains numbers: r ( 4.5, 1.0 ) 10.5 7 
Numbers are: 45101057

I want to find a way to assign the numbers to variable. So for example using the following string: r ( 4.5, 1.0 ) 10.5 7 (Assuming a,b,c,d are already declared) I want this:

a = 4.5
b = 1.0
c = 10.5 
d = 7

Upvotes: 0

Views: 900

Answers (3)

kmell96
kmell96

Reputation: 1465

Try this (it uses a second scanner to try to parse each token as a Double; if it's not a double, the parsing will fail):

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

    System.out.print("Enter string that contains numbers: ");
    String str = sc.nextLine();

    Scanner token = new Scanner(str);
    while token.hasNext() {
         String tokenStr = token.next();
         try {
             double d = Double.parseDouble(tokenStr);
             // YOUR CODE: do something with d here, such as appending
             // it to an array, assigning it to a var, or printing it out.

         } catch (NumberFormatException e) {
             // no op
         }
    }
}

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727067

If you would like to keep floating-point numbers and separators, you must include dot character and space, in addition to decimal digits, into the replacement regex:

numbers = str.replaceAll("[^0-9. ]", "");

Demo.

Once you have the string, separating out the individual numbers can be done using the technique discussed in this Q&A: Convert a string of numbers into an array.

Upvotes: 1

Makoto
Makoto

Reputation: 106508

Having variables in that fashion is only going to be useful if you're guaranteed that you have four values in your file. For flexibility's sake, it's better to place this in a list instead.

List<Double> numbers = new ArrayList<>();
// assuming str already has the numbers...
for(String s : str.split(" ") {
    numbers.add(Double.parseDouble(s));
}

Declaring these as individual variables uses 99% of the same approach above, just swapping out a list for the individual values. I leave that as an exercise for the reader.

Upvotes: 0

Related Questions