Scope of a non-static method printing a vector of objects

Hello everyone,
I'm new to using the java.util.Vector package. I wanted to create a print out of all the objects of class "Student" that I created within a "students" vector. My problem is that scope is causing a compile error when calling the print method acting on the students vector. Anybody got any ideas? Further to this I'd like to keep my printVec() generic enough so that I can create a class "Teachers" and a "teachers" array and make the the printVec() method able to print both, ie;
teachers.printVec()
students.printVec()My code is below;
import java.io.*;
import java.lang.*;
import java.util.*;
class Example {
   public static void main(String[] args){
      Vector<Student> students = new Vector<Student>();
      students.addElement(new Student("Billy"));
      students.addElement(new Student("Ryan"));
      students.addElement(new Student("William"));
      students.addElement(new Student("Jason"));
      //the below print algorithm works...
      for(int i=0;i<students.size();i++)
         System.out.println(i+" "+students.elementAt(i).getName());
         //however i can't get this following one to work...
//       students.printVec();
         //uncomment above line
   public void printVec(){
//      for(int i=0;i<students.size();i++)//uncomment these lines
//         System.out.println(i+" "+students.elementAt(i).getName());//uncomment these lines
        //uncomment above two lines
class Student{
   //constructors
   public Student(String name){
      this.name = name;
      this.subjectNumber = -1;
      this.tutorialNumber = -1;
   //methods
   public String getName(){
      return name;
   //fields
   private String name;
   private int subjectNumber;
   private int tutorialNumber;
}

You should use an Iterator, not get(). And youshould
prefer ArrayList over Vector.Why are you telling me this? I know this already... I
was reusing the OP's way so that he/she/it could see
it done his/her/its way.I have no way of knowing what you do or don't know. I only saw crap code, so I corrected it.
>
That won't work if more than one student has thesame
name, and it's a very counterintuitive way to
approach the problem.Um... yes, it will work if more than one student has
the same name. It will not work if students in the
Vector share memory. It searches for memory, not the
name.Actually, we're both wrong.
If Student overrides equals to be based on name, then it won't work as I described. If not, then it will work.
It only looks at "memory" if Student does not override equals.
I didn't think that there would be a problem with
memory, but if there is, simply add a counter:????
What are you talking about?
public static void printVec(Vector<Student> students)
int count = 0;
for (Student s : students) {
System.out.println((count++) + " " +
+ " " + s.getName());
}That's the right way to do it, but that has nothing to do with "a problem with memory."

Similar Messages

  • Non-static method cannot be referenced from a static context

    Hey
    Im not the best java programmer, im trying to teach myself, im writing a program with the code below.
    iv run into a problem, i want to call the readFile method but i cant call a non static method from a static context can anyone help?
    import java.io.*;
    import java.util.*;
    public class Trent
    String processArray[][]=new String[20][2];
    public static void main(String args[])
    String fName;
    System.out.print("Enter File Name:");
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    fName="0";
    while (fName=="0"){
    try {
    fName = br.readLine();
    System.out.println(fName);
    readFile(fName);
    catch (IOException ioe)
    System.out.println("IO error trying to read File Name");
    System.exit(1);
    public void readFile(String fiName) throws IOException {
    File inputFile = new File(fiName); //open file for reading
         FileReader in = new FileReader(inputFile); //
    BufferedReader br = new BufferedReader(
    new FileReader(inputFile));
    String first=br.readLine();
    System.out.println(first);
    StringTokenizer st = new StringTokenizer(first);
    while (st.hasMoreTokens()) {
    String dat1=st.nextToken();
    int y=0;
    for (int x=0;x<=3;){
    processArray[y][x] = dat1;
    System.out.println(y + x + "==" + processArray[y][x]);
    x++;
    }

    Hi am getting the same error in my jsp page:
    Hi,
    my adduser.jsp page consist of form with field username,groupid like.
    I am forwarding this page to insertuser.jsp. my aim is that when I submit adduser.jsp page then the field filled in form should insert into the usertable.The insertuser.jsp is like:
    <% String USERID=request.getParameter("id");
    String NAME=request.getParameter("name");
    String GROUPID=request.getParameter("group");
    try {
    Class.forName("com.mysql.jdbc.Driver");
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mynewdatabase","root", "root123");
    PreparedStatement st;
    st = con.prepareStatement("Insert into user values (1,2,4)");
    st.setString(1,USERID);
    st.setString(2,GROUPID);
    st.setString(4,NAME);
    // PreparedStatement.executeUpdate();//
    }catch(Exception ex){
    System.out.println("Illegal operation");
    %>
    But showing error at the marked lines lines as:non static method executeupdate can not be referenced from static context.
    Really Speaking I am newbie in this java world.
    whether you have any other solution for above issue?
    waiting Your valuable suggestion.
    Thanks and regards
    haresh

  • Non static method

    I have the following:
    import java.io.*;
    import java.util.*;
    public class BranchB2
         public static void main(String[] args)
              int pathCost, source, destination, count=0;
              int userSource, userDestination;
              String tempRead;
              ArrayList edge = new ArrayList();
              System.out.print("Start: ");
              userSource = read();
              System.out.print("End: ");
              userDestination = read();
              if(userSource == -1 || userDestination == -1)
                   System.out.println("Error in entry, Program will now exit!");
                   System.exit(0);
            try
                   FileReader file = new FileReader("graph_info - TUTE 2.txt");
                   BufferedReader fileInput = new BufferedReader(file);
                   String str = "";
                   while ((str = fileInput.readLine()) != null)//Read every line until EOF
                        String []splits = str.split(" ");
                        source = Integer.parseInt(splits[0]);
                        destination = Integer.parseInt(splits[1]);
                        pathCost = Integer.parseInt(splits[2]);
                        edge.add(new Edge(pathCost, source, destination));
                       count++;
              catch (IOException e)
                   System.out.println("ERROR: Cannot Read File!");
              int size = edge.size();
              //Create the array of linked lists
              ArrayList path = new ArrayList();
              ArrayList pathArray[] = new ArrayList[20];
              for(int i = 0; i < pathArray.length; i++)
                   pathArray[i] = new ArrayList();
              int place = runFirst(pathArray, size, userSource, edge);
              //display(place, pathArray);
              int add=0;
              sort(pathArray);
              /* This is the first part of the program,   *
               * It first gets an initial set of values   *
               * to be stored in the array so the second  *
               * can run.                                             *
              int place=0;
              for(int j=0; j<size; j++)
                   Edge temp = (Edge)edge.get(j);
                   if(temp.getSource() == userSource)
                        pathArray[place].add(new Edge(temp));
                        temp.setVisited(true);
                        place++;
              DISPLAY
              int test = place;//pathArray[0].size();
              System.out.println("Test = " + test);
              for(int k=0; k<test; k++)
                   for(int
                   Edge tempDisplay = (Edge)pathArray[k].get(0);
                   System.out.println("Start: " + tempDisplay);
         public static void display(int place, ArrayList pathArray[])
              int test = place;
              System.out.println("Test = " + test);
              for(int k=0; k<test; k++)
                   Edge tempDisplay = (Edge)pathArray[k].get(0);
                   System.out.println("Start: " + tempDisplay);
         public static int runFirst(ArrayList pathArray[], int size, int userSource, ArrayList edge)
              /* This is the first part of the program,   *
               * It first gets an initial set of values   *
               * to be stored in the array so the second  *
               * can run.                                             */
              int place=0;
              for(int j=0; j<size; j++)
                   Edge temp = (Edge)edge.get(j);
                   if(temp.getSource() == userSource)
                        pathArray[place].add(new Edge(temp));
                        temp.setVisited(true);
                        place++;     
              //System.out.println(pathArray[0].get(0));
              //System.out.println(pathArray[1].get(0));
              return place;
         public void sort(ArrayList pathArray[])
              int ff = pathArray.length;
              System.out.println(ff);
              //for(int out=pathArray.length; out>1; out--)
                   //for(int in=0; in<out; in++)
                        int one=0, two=0;
                        int sizeList = pathArray[0].size();
                        for(int current=0; current<sizeList; current++)
                             Edge tempOne = (Edge)pathArray[0].get(current);
                             one = one + tempOne.getPathCost();
                        int sizeListNext = pathArray[1].size();
                        for(int current=0; current<sizeListNext; current++)
                             Edge tempDisplay = (Edge)pathArray[1].get(current);
                             two = two + tempDisplay.getPathCost();
                        /*if(one > two)
                             ArrayList temp = pathArray[0];
                             pathArray[0] = pathArray[1];
                             pathArray[1] = temp;     
                        System.out.println("one: " + one + "two: " + two);
         public static int read()
              int value = -1;
              try
                   InputStreamReader isr = new InputStreamReader(System.in);
                   BufferedReader br = new BufferedReader(isr);
                   String tempRead = br.readLine();
                   value = Integer.parseInt(tempRead);
              catch (IOException e)
                   System.out.println("ERROR: Cannot read keyboard!");
              return value;
    }i get the error:
    C:\Users\Taurus\Desktop\University\AMI - 4517\Assignment\branchb>javac BranchB2.
    java
    BranchB2.java:77: non-static method sort(java.util.ArrayList[]) cannot be refere
    nced from a static context
                    sort(pathArray);
                    ^
    1 error
    C:\Users\Taurus\Desktop\University\AMI - 4517\Assignment\branchb>Why am I getthing this as sort is not static?

    Yorkroad's tip is correct. You'll want to create an instance of the class within the main function, then call all methods using that instance. This will allow you to have all your methods non-static. (The error is because main is a static method).
    A good way to avoid that problem is to have your main function in its own seperate class in order to maintain a truly object-oriented methodology.

  • Calling a non-static method from another Class

    Hello forum experts:
    Please excuse me for my poor Java vocabulary. I am a newbie and requesting for help. So please bear with me! I am listing below the program flow to enable the experts understand the problem and guide me towards a solution.
    1. ClassA instantiates ClassB to create an object instance, say ObjB1 that
        populates a JTable.
    2. User selects a row in the table and then clicks a button on the icon toolbar
        which is part of UIMenu class.
    3. This user action is to invoke a method UpdateDatabase() of object ObjB1. Now I want to call this method from UIMenu class.
    (a). I could create a new instance ObjB2 of ClassB and call UpdateDatabase(),
                                      == OR ==
    (b). I could declare UpdateDatabase() as static and call this method without
         creating a new instance of ClassB.With option (a), I will be looking at two different object instances.The UpdateDatabase() method manipulates
    object specific data.
    With option (b), if I declare the method as static, the variables used in the method would also have to be static.
    The variables, in which case, would not be object specific.
    Is there a way or technique in Java that will allow me to reference the UpdateDatabase() method of the existing
    object ObjB1 without requiring me to use static variables? In other words, call non-static methods in a static
    way?
    Any ideas or thoughts will be of tremendous help. Thanks in advance.

    Hello Forum:
    Danny_From_Tower, Encephalatic: Thank you both for your responses.
    Here is what I have done so far. I have a button called "btnAccept" created in the class MyMenu.
    and declared as public.
    public class MyMenu {
        public JButton btnAccept;
         //Constructor
         public MyMenu()     {
              btnAccept = new JButton("Accept");
    }     I instantiate an object for MyMenu class in the main application class MyApp.
    public class MyApp {
         private     MyMenu menu;
         //Constructor     
         public MyApp(){
              menu = new MyMenu();     
         public void openOrder(){
               MyGUI MyIntFrame = new MyGUI(menu.btnAccept);          
    }I pass this button all the way down to the class detail02. Now I want to set up a listener for this
    button in the class detail02. I am not able to do this.
    public class MyGUI {
         private JButton acceptButton;
         private detail02 dtl1 = new detail02(acceptButton);
         //Constructor
         public AppGUI(JButton iButton){
         acceptButton = iButton;
    public class detail02{
        private JButton acceptButton;
        //Constructor
        public detail02(JButton iButton){
          acceptButton = iButton;
          acceptButton.addActionListener(new acceptListener());               
       //method
        private void acceptListener_actionPerformed(ActionEvent e){
           System.out.println("Menu item [" + e.getActionCommand(  ) + "] was pressed.");
        class acceptListener implements ActionListener {       
            public void actionPerformed(ActionEvent e) {
                   acceptListener_actionPerformed(e);
    }  I am not able to get the button Listener to work. I get NullPointerException at this line
              acceptButton.addActionListener(new acceptListener());in the class detail02.
    Is this the right way? Or is there a better way of accomplishing my objective?
    Please help. Your inputs are precious! Thank you very much for your time!

  • Abstract method versus static and non-static methods

    For my own curiosity, what is an abstract method as opposed to static or non-static method?
    Thanks

    >
    Following this logic, is this why the "public static
    void main" 0r "Main" method always has to be used
    before can application can be run: because it belongs
    to the class (class file)?
    Yes! Obviously, when Java starts up, there are no instances around, so the initial method has to be a static (i.e. class) one. The name main comes from Java's close association with C.
    RObin

  • Non static method cannot be referenced from a non static context

    Dear all
    I am getting the above error message in my program.
    public void testing(Vector XY){
    RecStore.checkUnits(XY);
    }method checkUnits is non static and cannont be called from a non static context. I don't see the word static anywhere...
    I have done a wider search throughout the main class and I'm haven't got any static their either.
    Any ideas?
    Thanks
    Dan

    Yup
    I had pared down my code, infact it is being called from within a large if statement.Irrelevant.
    But the same thing still holds that there is no static keyword used.Read my previous post. Calling checkUnits using the class name:
    RecStore.checkUnits(XY);implies a static context--in order for that call to work, checkUnits must be static. That's what your error message is saying--you are trying to call the non-static method "checkUnits" from the static context of using the class name "RecStore."

  • Non-static method cannot be referenced from a static context....again sry

    Hey, I know you guys have probably seen a lot of these, but its for an assignment and I need some help. The error I'm getting is: non-static method printHistory() cannot be referenced from a static context. Here are the classes effected
    public class BankAccount {
    private static int nextAccountNumber = 1000;
    //used to generate account numbers
    private String owner; //name of person who owns the account
    private int accountNumber; //a valid and unique account number;
    private double balance; //amount of money in the account
    private TransactionHistory transactions; //collection of past transactions
    private Transaction transaction;
    //constructor
    public BankAccount(String anOwnerName){
    owner = anOwnerName;
    accountNumber = nextAccountNumber++;
    balance = 0.0;
    transactions = new TransactionHistory();
    //public String getOwner() {
    public void deposit(double anAmount ){
         balance=balance+anAmount;
         transaction=new Transaction(TransactionType.DEPOSIT,accountNumber,anAmount,balance);
         transactions.add(transaction);
    //public void withdraw(double anAmount){
    //public String toString() {
    ***public void printHistory(){
         TransactionHistory.printHistory();
    AND
    public class TransactionHistory {
    final static int CAPACITY = 6; //maximum number of transactions that can be remembered
    //intentionally set low to make testing easier
    private Transaction[] transactions = new Transaction[CAPACITY];
    //array to store transaction objects
    private int size = 0;
    //the number of actual Transaction objects in the collection
    public void add(Transaction aTransaction){
         if (size>5){
         transactions[0]=transactions[1];
         transactions[1]=transactions[2];
         transactions[2]=transactions[3];
         transactions[3]=transactions[4];
         transactions[4]=transactions[5];
         transactions[5]=aTransaction;     
         transactions[size]=aTransaction;
         size=size++;
    public int size() {
         return size;
    ***public void printHistory() {
         for(int i=0;i<6;i++){
              System.out.println(transactions);
    //public void printHistory(int n){
    The project still isn't finished, so thats why some code is commented out. The line with *** infront on it are the methods directly effected, I think. Any help would be great.

    In Java, static means "something pertaining to an object class". Often, the term class is substituted for static, as in "class method" or "class variable." Non-static, on the other hand, means "something pertaining to an actual instance of an object. Similarly, the term +instance+ is often substituted for +non-static+, as in "instance method" or "instance variable."
    The error comes about because static members (methods, variables, classes, etc.) don't require an instance of the object to be accessed; they belong to the class. But a non-static member belongs to an instance -- an individual object. There's no way in a static context to know which instance's variable to use or method to call. Indeed, there may not be any instances at all! Thus, the compiler happily tells you that you can't access an instance member (non-static) from a class context (static).
    ~

  • Non-static method paint cannot be referenced from static context

    i cant seem to figure out this error dealing method paint:
    public class TemplateCanvas extends Canvas implements Runnable {
        //static
        public static final int STATE_IDLE      = 0;
        public static final int STATE_ACTIVE    = 1;
        public static final int STATE_DONE      = 2;
        private int     width;
        private int     height;
        private Font    font;
        private Command start;   
        private int state;
        private String message;
        public TemplateCanvas() {
            width = getWidth();
            height = getHeight();       
            font = Font.getDefaultFont();
            //// set up a command button to start network fetch
            start = new Command("Start", Command.SCREEN, 1);
            addCommand(start);
        public void paint(Graphics g) {
            g.setColor(0xffffff);
            g.fillRect(0, 0, width, height);
            g.setColor(0);
            g.setFont(font);
            if (state == STATE_ACTIVE) {
                Animation.paint(g);
            } else if (state == STATE_DONE) {
                g.drawString(message, width >> 1, height >> 1, Graphics.TOP | Graphics.HCENTER);
        public void commandAction(Command c, Displayable d) {
            if (c == start) {
                removeCommand(start);
                //// start fetching in a new thread
                Thread t = new Thread(this);
                t.start();
        public void run() {
            state = STATE_ACTIVE;
            //// start network fetch
            Network network = new Network();
            network.start();
            //// start busy animation
            Animation anim = new Animation(this);
            anim.start();
            //// wait for network to finish
            synchronized (network) {
                try {
                    wait();
                } catch (InterruptedException ie) { }
            //// end animation
            anim.end();
            //// get message from network
            message = network.getResult();
            //// repaint message
            state = STATE_DONE;
            repaint();
    }TemplateCanvas.java:38: non-static method paint(javax.microedition.lcdui.Graphics) cannot be referenced from a static context

    Animation.paint(g); paint() is not a static method. That means you have to call it on an instance of an Animation class (an object), not on the class itself. This is designed this way because the paint() method uses variables that have to be instantiated, so if you don't have an instance to use, it can't access the variables it needs. Static methods don't use instance variables, they only use what's passed in to them, so they don't need to be called on an object. Hope that was clear.

  • Non-static method setUp() cannot be referenced  (error)

    Hi;
    I have this error
    "findContainer.java": non-static method setUp() cannot be referenced from a static context at line 10, column 26
    everytime i am trying to make this call
    jade.core.AddContTry.setUp();in
    public class findContainer {
      public findContainer() {}
        public void sUp(){
        System.out.println("please wait, this is first try to find he agents in the main container"+"\n");
        jade.core.AddContTry.setUp();
    this setup() method
    is written as follows
    public void AddContTry () {
    public void setUp(){
      AID[] list= null;
      try {
        MyMainContainer = myprofile.getMain();
        System.out.println("\n"+"This is the new container created in case of failure"+"\n");
        list = MyMainCont.agentNames();
        for (int i=0; i<list.length; i++){
          System.out.println("names = " + list.toString() + " \n");
    catch (ProfileException pe) { System.out.println("there is not main container");
    could you please help me?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    My guess is that it is throwing a NullPointerException because you have not set 'a' to be anything.
    The sample code you provided does not make sense.
    AddContTry is a method in the code but you are using it like a class.
    You have to set the following before you can use the object 'a'
    AddContTry a = // something
    I am just guessing here but can you write
    AddContTry a = new AddContTry();
    a.setUp();
    Note, If this is the case, the code in setUp should be in the constructor.

  • Non-static method getRealPath cannot be referenced from a static context

    Hi, I'm fairly new to java and servlets, I get the following error referencing the line denoted in the code snippet with a ">>" I don't understand why I am getting this error message?
    Message: non-static method getRealPath(java.lang.String) cannot be referenced from a static context
    public class events extends HttpServlet implements SingleThreadModel {
      private static final String CONTENT_TYPE = "text/html";
      //Initialize global variables
      public Document xmlDocument;
      public HttpSession theSession;
      public RequestDispatcher pageInit;
      public RequestDispatcher pageHeader;
      public RequestDispatcher pageFooter;
      public String path;
      public void setPath(){
    path = getServletContext.getRealPath( "/" );  }
      public void init() throws ServletException {
      }

    Ok More Code, I am weary of posting too much? I don't know why come to think of it?
    package altitude;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    import java.util.*;
    import org.jdom.*;
    import altitude.sysVar;
    public class events extends HttpServlet implements SingleThreadModel {
      private static final String CONTENT_TYPE = "text/html";
      //Initialize global variables
      public Document xmlDocument;
      public HttpSession theSession;
      public RequestDispatcher pageInit;
      public RequestDispatcher pageHeader;
      public RequestDispatcher pageFooter;
      public String path;
      public void getRealPath(){
        path = ServletContext.getRealPath( "/" );
      public void init() throws ServletException {
      //Process the HTTP Get request
      public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
        //Initialise some Global Variables
        theSession = request.getSession( true );
        doPage( request, response );
      //Process the HTTP Post request
      public void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
        //Initialise some Global Variables
        theSession = request.getSession( true );
        doPage( request, response );
    public void doPage( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
        //Initialise the variables and get the parameters from the query string.
        String eventID = request.getParameter( "eventID" );
        String dateFrom = request.getParameter( "dateFrom" );
        String dateTo = request.getParameter( "dateTo" );
        theSession.setAttribute( "Page Title", sysVar.servletTitle_events);
        Calendar theCalendar = Calendar.getInstance();
        RequestDispatcher pageInit = request.getRequestDispatcher( sysVar.servlet_initSession );
        pageInit.include( request, response );
        RequestDispatcher pageHeader = request.getRequestDispatcher( theSession.getAttribute( "Skin Directory" ) + sysVar.page_header );
        RequestDispatcher pageBody = request.getRequestDispatcher( sysVar.servletJsp_events );
        RequestDispatcher pageFooter = request.getRequestDispatcher( theSession.getAttribute( "Skin Directory" ) + sysVar.page_footer );
        //Initailize the site for this visitor this sets up the skin, and any customisations that may exist.
        //load variables, objects in to the session
        theSession.setAttribute( "Xml Document Object",  path + sysVar.data_events );
        pageHeader.include( request, response );
        pageBody.include( request, response );
        pageFooter.include( request, response );
        //remove the variables and the objects from the session
        theSession.setAttribute( "Xml Document Object", "" );
      //Clean up resources
      public void destroy() {
    }

  • Non-static method/object cannot be referenced from a static context...?????

    What does this mean. I know about static, but I don't understand why I get this so many times.
    I try to do something pretty normal and this is what I get a lot of times. I mean: the main() method should be static right? Then what good is the main() method if you cannot let it do stuff for you like this:
    public class Test extends JFrame
        public Test
            setSize( 100, 100 );
            show();
    public static main( String args[] )
        Test window = new Test();
        draw();
    public void draw()
        blablabla whatever I want to do, a lot of times I can't.....
    }Why is this, what is the reason for Java to forbid this and what can I do about it?

    Your draw() method, since it isn't defined as static is considered by Java to be part of your Test object; hence, it can only be invoked in the context of an existing instance of your object. In other words, any Java program that wanted to use your draw() method would have to create an instance of your Test class using something likemyTest = new Test()Your main method, however, is something different. Since you want to execute your class as a program, the Java run-time environment needs to have standard starting point. This starting point is the main method. The problem is that the main method must be static, because the run-time environment cannot be expected to know beforehand the correct way to create an instance of your class so that non-static methods can be invoked. The drawback is that your main method can only directly access methods that are defined as static.
    There are two possible solutions to this problem, and which of the two you want to use depends on the object-oriented nature of your program.
    On the one hand, if your draw() method is closely tied to the object itself, if the draw() method is actually drawing your object or a part of it, it should be left as an instance method, and you should simpy use the instance of the object you created in your main method:public static main( String args[] )
        Test window = new Test();
        // maybe some code to generate something to draw???
        window.draw();
    }This is what I think you are trying to do.
    On the other hand, if your draw() method was some kind of universal method that didn't depend in any way on the current configuration of your instance, you could simply define draw() as static at which point your main method (or a method in an external class) could invoke it directly, without a corresponding instance. But if you did that, the draw() method itself would only be able to access static variables and methods.
    Doug

  • Non-static method getIDnumber() cannot be referenced from a static context

    Student.java
    public class Student
         private int IDnumber;
         private int hours;
         private int points;
         public Student()
       IDnumber = 9999;
       points = 12;
       hours = 3;
         public void setIDnumber(int number)
         IDnumber = number;
       public int getIDnumber()
         return IDnumber;
       public void setHours(int number)
       hours = number;
       public int getHours()
       return hours;
       public void setPoints(int number)
       points = number;
       public int getPoints()
       return points;
         public void showIDnumber()
       System.out.println("ID Number is " + IDnumber);
       public void showHours()
       System.out.println("Credit Hours are " + hours);
       public void showPoints()
       System.out.println("Points Earned are " + points);
       public double getGradePoint()
       return (double) (points / hours);
    ShowStudent.java
    public class ShowStudent
         public static void main(String[] args)
              Student learner = new Student();
              int IDnumber;
              int points;
              int hours;
              IDnumber = Student.getIDnumber();
              points = Student.getPoints();
              hours = Student.getHours();
              System.out.println("ID number is " + IDnumber);
              System.out.println("Hours are " + hours);
              System.out.println("Points are " + points);
    Here I get the following.  How do I fix this?  Thanks.
    ShowStudent.java:9: non-static method getIDnumber() cannot be referenced from a
    static context
    IDnumber = Student.getIDnumber();
    ^
    ShowStudent.java:10: non-static method getPoints() cannot be referenced from a
    static context
    points = Student.getPoints();
    ^
    ShowStudent.java:11: non-static method getHours() cannot be referenced from a s
    tatic context
    hours = Student.getHours();
    ^
    3 errors

    You have to get the ID number of a particular instance i.e. IDnumber = learner.getIDnumber();

  • Non-static method getPerimeter() cannot be referenced from a static context

    I am getting this error message. I assume it is because getArea( ) and getPerimeter( ) are nonstatic and main is static? Can somebody help me? Thanks in advance!
    Error messages:
    non-static method getArea() cannot be referenced from a static context
              System.out.println("\nArea: " + onePlace.format(getArea()));
    non-static method getPerimeter() cannot be referenced from a static context
              System.out.println("Perimeter: " + onePlace.format(getPerimeter()));
    import java.util.Scanner;
    import java.text.DecimalFormat;
    public class Rectangle
         public double length;
         public double width;
         public Rectangle()
              length = 0;
              width = 0;
         public double getLength()
              return length;
         public double getWidth()
              return width;
         public void setLength(double length)
              this.length = length;
         public void setWidth(double width)
              this.width = width;
         public double getArea()
              return (length * width);
    /*     public double area(Rectangle R)
              double area = length * width;
              return area;
         public double getPerimeter()
              return ((length * 2) + (width * 2));
    /*     public double perimeter(Rectangle R)
              double perimeter = (length * 2) + (width * 2);
              return perimeter;
    /*     public String toString()
              double area = 0;
              double perimeter = 0;
              return "Area: " + area + "\tPerimeter: " + perimeter;
         public static void main(String [] args)
              DecimalFormat onePlace = new DecimalFormat("#0.0");
              Rectangle R = new Rectangle();
              Rectangle L = new Rectangle();
              Rectangle W = new Rectangle();
              Scanner input = new Scanner(System.in);
              System.out.println("Enter length of rectangle: ");
              L.setLength(input.nextDouble());
              System.out.println("\nEnter width of rectangle: ");
              W.setWidth(input.nextDouble());
              System.out.println("\nArea: " + onePlace.format(getArea()));
              System.out.println("Perimeter: " + onePlace.format(getPerimeter()));
    //          System.out.println(R.toString());
    }

    For some reason, something isn't being read.
    This is what I get:
    Enter length of rectangle:
    2
    Enter width of rectangle:
    4
    Area: 0.0
    Perimeter: 0.0
    Press any key to continue . . .
    Is it what I have to scan the input (L.setLength...)?
         public static void main(String [] args)
              DecimalFormat onePlace = new DecimalFormat("#0.0");
              Rectangle R = new Rectangle();
              Rectangle L = new Rectangle();
              Rectangle W = new Rectangle();
              Scanner input = new Scanner(System.in);
              System.out.println("Enter length of rectangle: ");
              L.setLength(input.nextDouble());
              System.out.println("\nEnter width of rectangle: ");
              W.setWidth(input.nextDouble());
              System.out.println("\nArea: " + onePlace.format(R.getArea()));
              System.out.println("Perimeter: " + onePlace.format(R.getPerimeter()));
    //          System.out.println(R.toString());
    }

  • Non-static method getContentPane() cannot be referenced from a static conte

    From this line I'm getting an error
    Container bmC = getContentPane();
    - non-static method getContentPane() cannot be referenced from a static context
    Aprecciate solution,
    thx

    The reason this is happening is that you can't call non-static methods from a static method. Non-static methods need an instance in order to be called. Static methods are not associated with an instance.

  • Non-static method close() cannot be referenced from a static context

    Friends,
    I am having a little help with some static and not static issues.
    I created a JMenuBar, it's in the file: SlideViewMenu.java
    One of the operations is File->Close and another is File->Exit.
    The listener is in the SlideViewMenu.java file. The listener needs to reference two non-static methods within SlideView.java.
    Here's some of the code:
    SlideViewMenu.java
    public class SlideViewMenu {
        public JMenuBar createMenuBar() {
        final Action openAction = new OpenAction();
        Action aboutAction = new AboutAction();
        ActionListener menuListener = new MenuActionListener();
        JMenuBar menuBar = new JMenuBar();
         // All the menu stuff works fine and is taken care of here.
       // Listener for Menu
       class MenuActionListener implements ActionListener {
         public void actionPerformed (ActionEvent actionEvent) {
              String selection = (String)actionEvent.getActionCommand();
             if (selection.equals("Close"))
              SlideViewFrame.close();
             else  SlideViewFrame.exit();
    }SlideView.java
    // Driver class
    public class SlideView {
         public static void main(String[] args) {
              ExitableJFrame f = new SlideViewFrame("SlideView");
                    // Stuff here, works fine.
    // Frame class
    class SlideViewFrame extends ExitableJFrame {
            // some things here, work fine.
         private SlideViewMenu menuBar = new SlideViewMenu();
         public SlideViewFrame(String title) {
         // Set title, layout, and background color
         super(title);
         setJMenuBar(menuBar.createMenuBar());
            // Stuff here works fine.
         // Handles doing stuff once the file has been selected
         public void setFileName(File fullFileName, String simpleName) {
            // Stuff here works fine.     
         // File->Close. clean up everything.
         public void close() {
              setTitle("SlideView");
              textArea.setText("");
              scrollBar.setVisible(false);
              textArea.setVisible(false);
              statsPanel.setVisible(false);
         // File->Exit.     
         public void exit() {
              System.exit(0);
    }The error I'm getting is:
    SlideViewMenu.java:50: non-static method close() cannot be referenced from a static context
    I don't get it?
    Thanks for all help.

    Making close() and exit() static would not solve the problem because close() requires access to nonstatic member variables/functions.
    Fortunately, that is not necessary. The real reason you are having a problem is that you don't have any way in your listener to access the main frame window, which is what the listener trying to control. You made a stab at gaining access by prefixing the function with the class name, but, as the compiler has informed you, that is only valid for static methods. If you think about it, you should see the sense in that, because, what if you had a number of frames and you executed className.close()? Which one would you close? All of them?
    Fortunately, there is an easy way out that ties the listener to the frame.
    SlideViewMenu.java:public class SlideViewMenu
      // Here's where we keep the link to the parent.
      private SlideViewFrame parentFrame;
      // Here's where we link to the parent.
      public JMenuBar createMenuBar(SlideViewFrame linkParentFrame)
        parentFrame = linkParentFrame;
        final Action openAction = new OpenAction();
        Action aboutAction = new AboutAction();
        ActionListener menuListener = new MenuActionListener();
        JMenuBar menuBar = new JMenuBar();
        // All the menu stuff works fine and is taken care of here.
      // Listener for Menu --- It is assumed that this is a non-static nested
      // class in SlideViewMenu. All SlideViewMenu variables are accessible from
      // here. If this is not the case, simply add a similar member variable
      //  to this class, initialize it with a constructor parameter, and
      // pass the SlideViewMenu parentFrame when the listener is
      // constructed.
      class MenuActionListener implements ActionListener
        public void actionPerformed (ActionEvent actionEvent)
          String selection = (String)actionEvent.getActionCommand();
          // Use parentFrame instead of class name.
          if (selection.equals("Close"))
              parentFrame.close();
            else
              parentFrame.exit();
    }SlideView.java// Driver class
    public class SlideView
      public static void main(String[] args)
        ExitableJFrame f = new SlideViewFrame("SlideView");
        // Stuff here, works fine.
    // Frame class
    class SlideViewFrame extends ExitableJFrame
      // some things here, work fine.
      private SlideViewMenu menuBar = new SlideViewMenu();
      public SlideViewFrame(String title)
        // Set title, layout, and background color
        super(title);
        //Here's where we set up the link.
        setJMenuBar(menuBar.createMenuBar(this));
      // Stuff here works fine.
      // Handles doing stuff once the file has been selected
      public void setFileName(File fullFileName, String simpleName)
        // Stuff here works fine.     
      // File->Close. clean up everything.
      public void close()
        setTitle("SlideView");
        textArea.setText("");
        scrollBar.setVisible(false);
        textArea.setVisible(false);
        statsPanel.setVisible(false);
      // File->Exit.
      public void exit()
        System.exit(0);
    }

Maybe you are looking for