Reputation: 21
I am working on an assignment in which I have been given the task of creating an arraylist of books. In my utility, I have a 3 arg constructor (String title, String author, double price).
In my main, I am to read the contents of a comma seperated value file (which contains a list of book titles, authors, and price all on seperate lines). We are to tokenize the contents of the file (which I am able to do), and we are then to instantiate an ArrayList that holds book objects only. For each book in the text file, we are to read the record, tokenize the record, and create a new book object from the tokenized field, and then add the object to the beginning of the arrraylist.
So my question is:
When I tokenize the file (using the String method split, as the assignment dictates), I end up with a line by line break down of the file (as I should). I think I then want to feed these values into my constructor, but the constructor only accepts args String, String, double, and of course my tokenized file is String, String, String. Is there any way to 'convert' (for lack of a better term) the last string value into a double (I know that doubles are primitive and Strings are not), but I thought i would ask you guys before I go back to the drawing board and figure out the correct way of doing this.
Thanks for your time.
Upvotes: 2
Views: 4378
Reputation: 1
Webtest w= new Webtest();
ArrayList<String> dd= w.getarraylist();
Object []array1 = dd.toArray();
double value = Double.parseDouble(dd.get(8));
System.out.println(value);
double x[]=new double[dd.size()];
for (int i = 0; i <x.length; i++) {
x[i]=Double.parseDouble(dd.get(i));
System.out.println(x[i]);
}
Upvotes: 0
Reputation:
You need to parse the string to a double, the code to do this would look like this:
Double num = Double.parseDouble(String);
Always make sure that the string is numberal before converting it else it will throw a error.
Upvotes: 0
Reputation: 89142
What you want to do is parse a string into a double (giving you the words so that you know what it's called).
In Java, you use
Double.parseDouble(String)
Upvotes: 2
Reputation: 138317
Double.parseDouble(d);
will convert String "1.23" into double 1.23. There is also the related Integer.parseInteger(i)
and Boolean.parseBoolean(b);
functions.
Upvotes: 2