3 Replies - 2455 Views - Last Post: 25 January 2011 - 04:33 PM Rate Topic: -----

#1 Guest_jarrod*


Reputation:

cannot call non-static method in a static method error?

Posted 25 January 2011 - 03:47 PM

i have to write a program to get the date from the gregorian calendar.
this is what i have but when i run the program i get an error saying that i cant call a non-static method into a static method.
any advice on how i can fix this?



import java.util.GregorianCalendar;
import java.util.Calendar;

public class Main {

    Calendar date = new GregorianCalendar();

    public int getYear(){
        int year = date.get(Calendar.YEAR);
        return year;
    }
    public int getMonth(){
        int month = date.get(Calendar.MONTH);
        return month;
    }
    public int getDay(){
        int day = date.get(Calendar.DAY_OF_MONTH);
        return day;
    }
    public static void main(String[] args) {

        System.out.println("Starting...");
        System.out.println("Today's date is (yyyymmdd) " + getYear() + getMonth() + getDay() +".");
        System.out.println("...Finished");

 }


Edited by Dogstopper: :code:

Is This A Good Question/Topic? 0

Replies To: cannot call non-static method in a static method error?

#2 Dogstopper  Icon User is offline

  • The Ninjaducky
  • member icon



Reputation: 2870
  • View blog
  • Posts: 11,025
  • Joined: 15-July 08

Re: cannot call non-static method in a static method error?

Posted 25 January 2011 - 03:57 PM

You make these calls inside main().
getYear() + getMonth() + getDay()

However, main is static, so is a class method, not an object method and cannot call non-static methods directly. Instead, you must instantiate an object and call the methods through them:

 public static void main(String[] args) {

        System.out.println("Starting...");
        Main m = new Main();
        System.out.println("Today's date is (yyyymmdd) " + m.getYear() + m.getMonth() + m.getDay() +".");
        System.out.println("...Finished");
 }


Was This Post Helpful? 2
  • +
  • -

#3 j_rod722  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 53
  • Joined: 25-January 11

Re: cannot call non-static method in a static method error?

Posted 25 January 2011 - 04:23 PM

thanks a lot.
Was This Post Helpful? 0
  • +
  • -

#4 Dogstopper  Icon User is offline

  • The Ninjaducky
  • member icon



Reputation: 2870
  • View blog
  • Posts: 11,025
  • Joined: 15-July 08

Re: cannot call non-static method in a static method error?

Posted 25 January 2011 - 04:33 PM

Glad I could help. :)
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1