I have a line in my main like so:
Date gameDate = DateFormat.parse(scanner.nextLine());
Essentially I want to scan in a date with util.Scanner
Which hits the error:
Cannot make a static reference to the non-static method parse(String) from the type DateFormat
Now, I've looked in to this error, but it doesn't seem as clear cut as this example.
How do I get round this?
parse()
is not a static method. It's an instance method. You need to create a DateFormat instance, and then call parse()
on this instance:
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date gameDate = dateFormat.parse(scanner.nextLine());
A static method belongs to a class. It doesn't make sense to call Person.getName()
. But it makes sense to call
Person pureferret = new Person("Pureferret");
String name = pureferret.getName();
You have to create an instance of DateFormat in order to call "parse". Only static methods can be called without istantiating an instance of the specified class. You can get an instance with the default DateFormat calling:
DateFormat.getInstance()
then you can call
DateFormat.getInstance().parse()
or you can define your own DateFormat using for example a subclass of DateFormat, as SimpleDateFormat.
DateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd");
myFormat.parse(myString);
Check here how you can customize it:
http://docs.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With