1

so far i have this

import java.util.ArrayList;

public class Sequence
{

private double[] sequence;


public Sequence(String s)
{
   String s = "903, 809, 719";
   System.out.println
   (java.util.Arrays.toString(s.split("\\.")));

}

Will this print the numbers in the string seperated by a comma?

Im then trying to to parse each individual String to get a double, storing these doubles in sequence. How do i do it?

Newish
  • 19
  • 2

4 Answers4

1

You should try a different split.

Try like this :

s.split(", ");

Hope this can help you.

mad_mask
  • 776
  • 2
  • 10
  • 31
1
    String str_arr[] = s.split(", ");
    for (String string : str_arr) {
        double d = Double.valueOf(s);
        //perform the necessary action here
    }
Balaji Katika
  • 2,835
  • 2
  • 21
  • 19
1

To answer your question, you're splitting your string with "\.", so no, it wont print the numbers separated by a comma.

To split the string by ", " simply change your code to be

s.split(", ");

In this particular scenario, I would personally split s into an array of strings and then add each element of that array of strings into an ArrayList of doubles so you can use them as you please later, like so

String[] doubleStrings = s.split(", ");
ArrayList<Double> doubleList = new ArrayList<Double>();

for(int i = 0;  i < doubleStrings.length; i++){
    doubleList.add(Double.parseDouble(doubleStrings[i]));    
}

By using an ArrayList, you can store each element of the split string in sequence, and thereby easily allowing you to print or process each Double however you please.

Alex Oczkowski
  • 434
  • 6
  • 10
0
 String[] ns = s.split(",");
 ArrayList<Double> doubles = new ArrayList<>();
 for(String q : ns)
 {
     doubles.add(new Double(Double.parseDouble(q)));
 }

You should have the double values in the doubles ArrayList. (make sure you try and catch a number format exception for the Double parsing)

Slow Trout
  • 492
  • 3
  • 13