Reputation: 15
I'm trying to covert an array of strings into an array of doubles. I'm fairly familiar with ArrayList<>() , but i see there is in an example code give, double[].
example: list = ["1" , "2" , "3"] desired return: number = [1 , 2 , 3]
public double[] ConversionNumber
{
double[] sequence = new double[list.size()];
for(String element:list){
double val = Double.parseDouble(element);
sequence.add(val)}
return sequence;
when i do this, i get an error in Bluej compiler: "cannot find symbol- method add(double).
What is a good way to solve this (i'm a beginner at Java).
thanks!
Upvotes: 1
Views: 2586
Reputation: 14011
Change your code here
for(String element:list){
double val = Double.parseDouble(element);
sequence.add(val)
}
to this if your list
is a List
:
for(int i=0;i<list.size();i++){
double val = Double.parseDouble(list.get(i));
sequence[i]=val;
}
if your list
is an Array
, then change to this:
for(int i=0;i<list.length;i++){
double val = Double.parseDouble(list[i]);
sequence[i]=val;
}
Upvotes: -2
Reputation: 1177
The error happens because arrays dont have an 'add' method. You will want to do something like:
double[] sequence = new double[list.length];
for(int i = 0; i < list.length; i++){
sequence[i] = Double.parseDouble(list[i]);
}
If list
is an actual List
not a String[]
as I assumed, you would do:
double[] sequence = new double[list.size()];
for(int i = 0; i < list.size(); i++){
sequence[i] = Double.parseDouble(list.get(i));
}
Upvotes: 0
Reputation: 318
Generally, if you're working with Collections, you work with collections the whole way. It's bad form to use Lists for one thing, but arrays for another. So it's advisable to do this with a List<Double>
instead of a double[]
public List<Double> parseDoubles(List<String> strings) {
List<Double> doubles = new ArrayList<>(strings.size());
for(String string : strings) {
doubles.add(new Double(string));
}
return doubles;
}
Upvotes: 1
Reputation: 9
Below code will work for your case:
java.util.List<String> list = java.util.Arrays.asList("1", "2", "3");
public double[] ConversionNumber() {
double[] sequence = new double[list.size()];
int i = 0;
for(String element:list){
double val = Double.parseDouble(element);
sequence[++i] = val;
}
return sequence;
}
Upvotes: 0
Reputation: 201409
If list
is an array, then list.size()
would fail. I think we can assume it should be a List<String>
. And you access an array by index. Also, I assume it should be an argument to your method. Next, Java convention for methods names is camelCase.
public double[] conversionNumber(List<String> list) {
double[] sequence = new double[list.size()];
int pos = 0;
for (String element : list) {
double val = Double.parseDouble(element);
sequence[pos++] = val; // <-- post-increment
}
return sequence;
}
Upvotes: 2