Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing date and running into a 'static reference to the non-static method' Error in java

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?

like image 719
AncientSwordRage Avatar asked Dec 09 '22 23:12

AncientSwordRage


2 Answers

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();
like image 152
JB Nizet Avatar answered May 08 '23 16:05

JB Nizet


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

like image 42
JayZee Avatar answered May 08 '23 17:05

JayZee