我遇到了编程课的问题。我们需要在逗号中分隔参数String以生成一个字符串数组,然后它需要解析每个单独的String以获得一个double,并按顺序存储这些双精度数。我们还给出了一些测试代码,输入参数如(" 1,5")。
这是我目前的代码
public class Sequence
{
private double[] sequence;
public Sequence(String s)
{
String[] res = s.split(",");
int length = res.length;
double[] result = new double[length];
for ( int i =0; i<length; i++) {
result[i] = Double.parseDouble(res[i])
}
}
我不确定从哪里开始,因为当我测试我的代码时,它会给出预期的结果。按顺序存储是什么意思?
答案 0 :(得分:2)
我已经更新了我的答案,这可能就是你要找的东西:
import java.util.Arrays;
public class Four {
public static void main(String[] args) {
String string = "1,2,10,4,9";
System.out.println(string);
double[] ds = getDouble(string);
for (int i = 0; i < ds.length; i++) {
System.out.println(ds[i]);
}
}
private static double[] getDouble(String string) {
double[] _double;
String[] _Strings = string.split(",");
_double = new double[_Strings.length];
for (int i = 0; i < _Strings.length; i++) {
_double[i] = Double.parseDouble(_Strings[i]);
}
Arrays.sort(_double);
return _double;
}
}
输出
答案 1 :(得分:1)
我会这样做:
public class Sequence {
private double[] sequence;
public void createSequence(int sequenceLength) {
sequence = new double[sequenceLength];
}
public void addToSequence(int index, double value) {
sequence[index] = value;
}
public double parseDouble(String s) {
return Double.parseDouble(s);
}
public String[] splitString(String s) {
return s.split(",");
}
@Override
public String toString() {
return Arrays.toString(sequence);
}
public static void main(String[] args) {
String str = "10.10,20.20,30.30";
Sequence sequence = new Sequence();
String[] splitted = sequence.splitString(str);
sequence.createSequence(splitted.length);
for (int i = 0; i < splitted.length; i++) {
double doubleValue = sequence.parseDouble(splitted[i]);
sequence.addToSequence(i, doubleValue);
}
System.out.println(sequence);
}
}
答案 2 :(得分:0)
将private double[] sequence;
更改为private Double[] sequence;
并使用下面的代码
public class Sequence {
private Double[] sequence;
public Sequence(String s) {
String separated[] = s.replace(" ", "").split(",");
ArrayList<Double> list = new ArrayList<>();
for (String num : separated) {
list.add(Double.parseDouble(num));
}
this.sequence = list.toArray(new Double[separated.length]);
}
}