-2

It's part of a school lab and I've researched and I can't find anything to accomplish this task. I'm reading in lines from a file using FileReader and BufferedReader. The data in the file is a name and an age in the following format:

John doe 20

Jane doe 30

etc. I already have code that will take each line and split as such: split[0] = {"John", "doe", "20"}

I need to get the "20" and store in an array of doubles such as double[0] = 20;

The reason it has to be a double and not Double is because that part of the code in the assignment is already written and I'm sure I cannot just decide to change everything and use a Double instead. How can I do this? Thank you in advance!

Isaac
  • 204
  • 2
  • 10

2 Answers2

6

Use Double#parseDouble.

As you can see the static method returns a primitive double and not an object Double:

public static double parseDouble(String s)

public static void main(String[] args) {
    String strNumber = "20";
    double myParsedDouble = Double.parseDouble(strNumber);

    System.out.println(myParsedDouble);
}
Erick G. Hagstrom
  • 4,873
  • 1
  • 24
  • 38
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
0

You'll want to get it into a for loop and start iterating... I'll just use List to manipulate the data, since we don't know how many matches there are (and thus, we cannot set up an array).

String[] startingArray; // Whatever you put in here
List<Double> endingList = new ArrayList<Double>();
for (String element : startingArray) {
    try {
        endingList.add(Double.parseDouble(element));
    } catch (NumberFormatException e) {
        // do nothing if it doesn't parse
        // note that catching exceptions do not have an adverse effect on performance
    }
}

// Either, if you want it in a Double[]... or
Double[] endingArray = endingList.toArray(new Double[endingList.size()]);

// If you want a double[], start iterating...
double[] endingArray = new double[endingList.size()];
for (int i = 0; i < endingList.size(); i++) {
    endingArray[0] = endingList.get(0);
}
ifly6
  • 5,003
  • 2
  • 24
  • 47