Reputation: 5131
I'm using the Stanford version of Eclipse as I'm learning from one of their videos, and using their blank project template.
Basically, I'm writing a custom class "Fraction". One of the constructors takes two numbers (doubles) and converts them to ints before storing them as numerator and denominator.
I've done
import java.lang.*;
public class Fraction {
And somewhere down I have
double numerator = Double(fractionComponents[0]); // fractionComponents is an array of string
double denominator = Double(fractionComponents[1]);
but I get the error:
The method Double(String) is undefined for the type Fraction.
I've also tried extending the class from Double.
Upvotes: 1
Views: 4781
Reputation: 9249
You want to use the static parseDouble
method, like so:
double numerator = Double.parseDouble(fractionComponents[0]);
double denominator = Double.parseDouble(fractionComponents[1]);
Note that you could also instantiate a Double
, but you should prefer to use the static method as it leaves the possibility for the implemention to cache Double
objects, and it's more clear to the reader what is going on - you're parsing a string for a double value.
If you were to use the constructor, it's not immediately clear what the type of fractionComponents[0]
is because there's both a Double(String)
and Double(double)
constructor.
Upvotes: 2
Reputation: 63
Following is the simple way to solve the problem
public class Fraction {
double numerator = Double.parseDouble(fractionComponents[0]);
double denominator = Double.parseDouble(fractionComponents[1]);
}
Upvotes: 1
Reputation: 36767
It probably should be
double numerator = new Double(fractionComponents[0]);
etc..
You're missing 'new'
Even then it's better to just do:
double numerator = Double.parseDouble(fractionComponents[0]);
to avoid unnecesarry unboxing.
Upvotes: 1
Reputation: 20061
You forgot new
:
double numerator = new Double(fractionComponents[0]);
double denominator = new Double(fractionComponents[1]);
If you're just interested in the primitive double
and not its object wrapper Double
then it's more common to write:
double numerator = Double.parseDouble(fractionComponents[0]);
double denominator = Double.parseDouble(fractionComponents[1]);
Upvotes: 4