如何将一个 String 放入一个数组中,然后放入一个 double 数组中?

How do I put a String into an array and then into an array of double?

目前我有这个:

public class sequence
{
private double[] sequence; 
// set up sequence by parsing s
//the numbers in s will be seperated by commas
public Sequence(String s)
{
  String [] terms = s.split (",");
  sequence = Double.parseDouble(terms);
}
}

我有的不起作用。但基本上我想要实现的是将 String 中的数字项(例如 1,2,3,4,5,6)移动到一个称为序列的双精度数组中。

您需要遍历条款。

String [] terms = s.split (",");
sequence = new double[terms.length];
for (int i = 0; i < terms.length; i++) {
    sequence[i] = Double.parseDouble(terms[i]);
}

Double.parseDouble取一个String和returns取一个Double。 您正在传递一个字符串数组。 更改您的代码以仅传递一个字符串。

public Sequence(String s) {
    String [] terms = s.split (",");
    sequence = new Double[terms.length];
    for (int i = 0; i < terms.length; i++) {
        sequence[i] = Double.parseDouble(terms[i]);
    }
 }

使用 Java 8 你可以做类似的事情

double[] sequence = Stream.of(s.split(",")).mapToDouble(Double::parseDouble).toArray();