Static context error

here is the code i am having issues with
import javax.swing.JOptionPane;
     public class GreekNumberDriver{
          public static void main (String [] args) {
               GreekNumbers Number  = new GreekNumbers ();
               String GreekNumber = GreekNumbers.sendGreekNumber ();
                    JOptionPane.showMessageDialog(null, GreekNumber);
          }when i try and complie i get this error:
GreekNumberDriver.java:9: non-static method sendGreekNumber() cannot be referenced from a static context
               String GreekNumber = GreekNumbers.sendGreekNumber ();
                                                ^here is the spot where the error is occuring in the origonal program
     public String sendGreekNumber (){
         return message;// sends main method the greek number analysis.
      }that snippet is part of a public class defined as
public class GreekNumbers() {
and i dont understand how it is non-static because i have never had this error before when i have used code identical to this.

DJ-Xen wrote:
here is the code i am having issues with
import javax.swing.JOptionPane;
     public class GreekNumberDriver{
          public static void main (String [] args) {
               GreekNumbers Number  = new GreekNumbers ();
               String GreekNumber = GreekNumbers.sendGreekNumber ();
                    JOptionPane.showMessageDialog(null, GreekNumber);
          }when i try and complie i get this error:
GreekNumberDriver.java:9: non-static method sendGreekNumber() cannot be referenced from a static context
               String GreekNumber = GreekNumbers.sendGreekNumber ();
                                                ^here is the spot where the error is occuring in the origonal program
     public String sendGreekNumber (){
return message;// sends main method the greek number analysis.
}that snippet is part of a public class defined as
public class GreekNumbers() {
and i dont understand how it is non-static because i have never had this error before when i have used code identical to this.This means that sendGreekNumber () is not a static method. to use it you have to do something like (new GreekNumbers()).sendGreekNumber ();

Similar Messages

  • Implementing Custom Event - non-static referencing in static context error

    Hi,
    I'm implementing a custom event, and I have problems adding my custom listeners to objects. I can't compile because I'm referencing a non-static method (my custom addListener method ) from a static context (a JFrame which contains static main).
    However, the same error occurs even if I try to add the custom listener to another class without the main function.
    Q1. Is the way I'm adding the listener wrong? Is there a way to resolve the non-static referencing error?
    Q2. From the examples online, I don't see people adding the Class name in front of addListener.
    Refering to the code below, if I remove "Data." in front of addDataUpdatelistener, I get the error:
    cannot resolve symbol method addDataUpdateListener (<anonymous DataUpdateListener>)
    I'm wondering if this is where the error is coming from.
    Below is a simplified version of my code. Thanks in advance!
    Cindy
    //dividers indicate contents are in separate source files
    //DataUpdateEvent Class
    public class DataUpdateEvent extends java.util.EventObject
         public DataUpdateEvent(Object eventSource)
              super(eventSource);
    //DataUpdateListener Interface
    public interface DataUpdateListener extends java.util.EventListener
      public void dataUpdateOccured(DataUpdateEvent event);
    //Data Class: contains data which is updated periodically. Needs to notify Display frame.
    class Data
    //do something to data
    //fire an event to notify listeners data has changed
    fireEvent(new DataUpdateEvent(this));
      private void fireEvent(DataUpdateEvent event)
           // Make a copy of the list and use this list to fire events.
           // This way listeners can be added and removed to and from
           // the original list in response to this event.
           Vector list;
           synchronized(this)
                list = (Vector)listeners.clone();
           for (int i=0; i < list.size(); i++)
                // Get the next listener and cast the object to right listener type.
               DataUpdateListener listener = (DataUpdateListener) list.elementAt(i);
               // Make a call to the method implemented by the listeners
                  // and defined in the listener interface object.
                  listener.dataUpdateOccured(event);
               System.out.println("event fired");
    public synchronized void addDataUpdateListener(DataUpdateListener listener)
         listeners.addElement(listener);
      public synchronized void removeDataUpdateListener(DataUpdateListener listener)
         listeners.removeElement(listener);
    //Display Class: creates a JFrame to display data
    public class Display extends javax.swing.JFrame
         public static void main(String args[])
              //display frame
              new Display().show();
         public Display()
         //ERROR OCCURS HERE:
         // Non-static method addDataUpdateListener (DataUpdateListener) cannot be referenced from a static context
         Data.addDataUpdateListener(new DataUpdateListener()
             public void dataUpdateOccured(DataUpdateEvent e)
                 System.out.println("Event Received!");
    //-----------------------------------------------------------

    Calling
        Data.someMethodName()is referencing a method in the Data class whose signature includes the 'static' modifier and
    might look something like this:
    class Data
        static void someMethodName() {}What you want is to add the listener to an instance of the Data class. It's just like adding
    an ActionListener to a JButton:
        JButton.addActionListener(new ActionListener()    // won't work
        JButton button = new JButton("button");           // instance of JButton
        button.addActionListener(new ActionListener()     // okay
    import java.awt.*;
    import java.awt.event.*;
    import java.util.Vector;
    import javax.swing.*;
    public class EventTest extends JFrame
        Data data;
        JLabel label;
        public EventTest()
            label = getLabel();
            data = new Data();
            // add listener to instance ('data') of Data
            data.addDataUpdateListener(new DataUpdateListener()
                public void dataUpdateOccured(DataUpdateEvent e)
                    System.out.println("Event Received!");
                    label.setText("count = " + e.getValue());
            getContentPane().add(label, "South");
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            setSize(300,200);
            setLocation(200,200);
            setVisible(true);
        private JLabel getLabel()
            label = new JLabel("  ", JLabel.CENTER);
            Dimension d = label.getPreferredSize();
            d.height = 25;
            label.setPreferredSize(d);
            return label;
        public static void main(String[] args)
            new EventTest();
    * DataUpdateEvent Class
    class DataUpdateEvent extends java.util.EventObject
        int value;
        public DataUpdateEvent(Object eventSource, int value)
            super(eventSource);
            this.value = value;
        public int getValue()
            return value;
    * DataUpdateListener Interface
    interface DataUpdateListener extends java.util.EventListener
        public void dataUpdateOccured(DataUpdateEvent event);
    * Data Class: contains data which is updated periodically.
    * Needs to notify Display frame.
    class Data
        Vector listeners;
        int count;
        public Data()
            listeners = new Vector();
            count = 0;
            new Thread(runner).start();
        private void increaseCount()
            count++;
            fireEvent(new DataUpdateEvent(this, count));
        private void fireEvent(DataUpdateEvent event)
            // Make a copy of the list and use this list to fire events.
            // This way listeners can be added and removed to and from
            // the original list in response to this event.
            Vector list;
            synchronized(this)
                list = (Vector)listeners.clone();
            for (int i=0; i < list.size(); i++)
                // Get the next listener and cast the object to right listener type.
                DataUpdateListener listener = (DataUpdateListener) list.elementAt(i);
                // Make a call to the method implemented by the listeners
                // and defined in the listener interface object.
                listener.dataUpdateOccured(event);
            System.out.println("event fired");
        public synchronized void addDataUpdateListener(DataUpdateListener listener)
            listeners.addElement(listener);
        public synchronized void removeDataUpdateListener(DataUpdateListener listener)
            listeners.removeElement(listener);
        private Runnable runner = new Runnable()
            public void run()
                boolean runit = true;
                while(runit)
                    increaseCount();
                    try
                        Thread.sleep(1000);
                    catch(InterruptedException ie)
                        System.err.println("interrupt: " + ie.getMessage());
                    if(count > 100)
                        runit = false;
    }

  • Static context error, nothing declared static, new instance isn't working

    I'm trying to get the IP address of a user using my applet. Nothing in my code is declared static.
    InetAddress IP = InetAddress.getAddress();I get non-static method getAddress cannot be referenced from a static context.
    I just read on another post with someone having a similar but not identical problem and someone replied saying you need to create a new instance. So I tried this:
    InetAddress IP = new InetAddress();
    //IP.getAddress();With this, I get the error: InetAddress(); is not public in java.net.InetAddress; cannot be accessed from an outside package
    What can I do? It's probably something simple.
    If you need code just ask, there's just alot of code and it might take awhile to recreate it.

    I'm trying to get the IP address of a user using my
    applet. Nothing in my code is declared static.
    InetAddress IP = InetAddress.getAddress();I get non-static method getAddress cannot be
    referenced from a static context.
    I just read on another post with someone having a
    similar but not identical problem and someone replied
    saying you need to create a new instance. So I tried
    this:
    InetAddress IP = new InetAddress();
    //IP.getAddress();With this, I get the error: InetAddress(); is not
    public in java.net.InetAddress; cannot be accessed
    from an outside package
    What can I do? It's probably something simple.
    If you need code just ask, there's just alot of code
    and it might take awhile to recreate it.In your first try the method you attempted to use can only be used in an instant of an InetAddress ie. ip.getAddress(). Therefore the compiler thought you were trying to call a static method that was really an instance method. On your second try you used the contructor of InetAddress which isn't public, so you can't use it. To make an InetAddress use any of the static methods of the InetAddress, which can be found at http://java.sun.com/j2se/1.4.1/docs/api/java/net/InetAddress.html

  • Help ! Problem with static context"

    What does it means ? "non-static variable this cannot be referenced from a static context"
    Error on NEW...
    import java.util.*;
    public class Test {
    public static void main (String[] args) {
    Reponse r = new Reponse ();
    r.demander ();
    System.out.println (r.getBP () + " " + r.getMP ());
    class Reponse {
    public void demander () {
    public int getBP () {
    return (nbBP);
    public int getMP () {
    return (nbMP);
    private int nbBP, nbMP;
    }

    georgemc wrote:
    phdk wrote:
    tsith wrote:
    phdk wrote:
    Why is your Reponse class not public?Because that would cause a compiler error?Thanks tsith!
    Maybe I misunderstand your reply.
    I am sure you had no idea what I meant. I'll try to make it clear.
    Is there any reason why it is defined as an inner class?It's not an inner class, it's a top-level class, hence tsith's responseActually, it is defined as an inner class, but the lack of code formatting makes this hard to see:
    import java.util.*;
    public class Test {
        public static void main (String[] args) {
            Reponse r = new Reponse ();
            r.demander ();
            System.out.println (r.getBP () + " " + r.getMP ());
        class Reponse {
            public void demander () {
            public int getBP () {
                return (nbBP);
            public int getMP () {
                return (nbMP);
            private int nbBP, nbMP;
    }Why an inner class? My guess is that the OP doesn't know what he is doing.

  • 2 errors: static context & java.lang.String

    I get the following 2 errors when I try and compile my code. What do I need to do in order to fix this problem?
    Any help appreciated.
    C:\>javac DraftD.java
    DraftD.java:54: non-static variable MAXIMUM cannot be referenced from a static context
    if(temp <= MAXIMUM)
    ^
    DraftD.java:54: operator <= cannot be applied to java.lang.String,int
    if(temp <= MAXIMUM)
    ^
    2 errors
    import java.io.*;
    import java.util.*;
    public class DraftD
    final int MAXIMUM = 20;
    public static void main(String[] args) throws IOException
    try
    Runtime program = Runtime.getRuntime();
    Process proc = program.exec("cmd.exe /c C:/ntpq.exe -p >C:/answer.txt");
    try{
    proc.waitFor();
    catch (InterruptedException e){}
    catch(IOException e1)
    int i = 0;
    BufferedReader br = new BufferedReader(new FileReader("C:/answer.txt"));
    String line = "";
    while ((line = br.readLine()) != null)
    i++;
    if(i==3) break;
    br.close();
    if(i==3)
    StringTokenizer st = new StringTokenizer(line," ");
         int k=1;
    while(st.hasMoreTokens())
         String temp = st.nextToken();
    if(k==2){
              String secondToken = temp;
    if(temp <= MAXIMUM)
              {System.out.println("less than Max");}
         k++;
    else System.out.println("less than 3 lines in file");
    System.exit(0);
    }

    You should use Integer.parseInt(temp); to convert temp to an int
    Because MAXIMUM is not static, every DraftD object will have one, that's the way properties work.
    main() however is static, and so there is only one between all the DraftD objects.
    It is a bit harder to explain with main(), but suppose we did this:public class ABC
      public int x;
      public static int getX()
        return x;
    ABC a = new ABC();
    ABC b = new ABC();
    a.x = 1;
    b.x = 2;
    int result = ABC.getX();should result be 1 or 2? it doesn't know which x to get, so the compiler complains.
    if MAXIMUM is a constant, you should make it public static final

  • Non-static variable being used in static context

    I am currently attempting to write a basic user login system using basic applets. I have two JTextFields named "userText" and "passText".
    What i am attempting to do is use the ".getText()" method to get the text out of the JTextField and verifying the string against a string already in a file using the bufferedReader, etc.
    However when i try to compare the string in the file with the one in the text field using the following code:
    if ((line.compareTo(username)) == 0)
    i get the following error...
    "non-static variable being used in a static context"
    Any ideas?

    The static method doesn't know about instances of the class instead you pass the instance to the method:
    static public void myMethod(MyClass instance, String var) {
      if(instance.line.compareTo(var))
    And then the call would be:
    MyClass.myMethod(anInstance, userName);

  • Non-static variable cant accessed from the static context..your suggestion

    Once again stuck in my own thinking, As per my knowledge there is a general error in java.
    i.e. 'Non-static variable cant accessed from static context....'
    Now the thing is that, When we are declaring any variables(non-static) and trying to access it within the same method, Its working perfectly fine.
    i.e.
    public class trial{
    ���������� public static void main(String ar[]){      ////static context
    ������������ int counter=0; ///Non static variable
    ������������ for(;counter<10;) {
    �������������� counter++;
    �������������� System.out.println("Value of counter = " + counter) ; ///working fine
    �������������� }
    ���������� }
    Now the question is that if we are trying to declare a variable out-side the method (Non-static) , Then we defenately face the error' Non-static varialble can't accessed from the static context', BUT here within the static context we declared the non-static variable and accessed it perfectly.
    Please give your valuable suggestions.
    Thanks,
    Jeff

    Once again stuck in my own thinking, As per my
    knowledge there is a general error in java.
    i.e. 'Non-static variable cant accessed from static
    context....'
    Now the thing is that, When we are declaring any
    variables(non-static) and trying to access it within
    the same method, Its working perfectly fine.
    i.e.
    public class trial{
    ���������� public static void
    main(String ar[]){      ////static context
    ������������ int counter=0; ///Non
    static variable
    ������������ for(;counter<10;) {
    �������������� counter++;
    ��������������
    System.out.println("Value
    of counter = " + counter) ; ///working fine
    �������������� }
    ���������� }
    w the question is that if we are trying to declare a
    variable out-side the method (Non-static) , Then we
    defenately face the error' Non-static varialble can't
    accessed from the static context', BUT here within
    the static context we declared the non-static
    variable and accessed it perfectly.
    Please give your valuable suggestions.
    Thanks,
    JeffHi,
    You are declaring a variable inside a static method,
    that means you are opening a static scope... i.e. static block internally...
    whatever the variable you declare inside a static block... will be static by default, even if you didn't add static while declaring...
    But if you put ... it will be considered as redundant by compiler.
    More over, static context does not get "this" pointer...
    that's the reason we refer to any non-static variables declared outside of any methods... by creating an object... this gives "this" pointer to static method controller.

  • Non-static variable from a static context

    This is the error i get . If i understand the error correctly it says im using a static variable when i shouldnt be? Or is it the other way round? below the error is the actual code....
    The error...
    Googler.java:27: non-static variable this cannot be referenced from a static context
              submitButton.addActionListener(new ButtonHandler());The code...
              JButton submitButton = new JButton("Submit Query");
              submitButton.addActionListener(new ButtonHandler());

    thanks for the response.
    I have already tried what you said but I tried it again anyway and i get the same error more less...
    Googler.java:28: non-static variable this cannot be referenced from a static context
              ButtonHandler buttonHandler = new ButtonHandler();here is part of my code
    public class Googler
      static JTextField input1, input2;
         public static void main(String[] args)
              JFrame myFrame = new JFrame("Googler v1.0");
              Container c = myFrame.getContentPane();
              JLabel lab1 = new JLabel("Enter Google Query:");
              JLabel lab2 = new JLabel("Enter Unique API Key:");
              input1 = new JTextField(15);
              input2 = new JTextField(15);
              JRadioButton radSearch = new JRadioButton("Search Query");
              JRadioButton radCached = new JRadioButton("Cached Query");
              JButton submitButton = new JButton("Submit Query");
              ButtonHandler buttonHandler = new ButtonHandler();
              submitButton.addActionListener(buttonHandler);
              ButtonGroup group = new ButtonGroup();
              group.add(radSearch);
              group.add(radCached);Ive tried declaring buttonHandler as a static variable and this dosn't work either. I've never had this problem before it must be something silly im missing...?
    Thanks
    Lee

  • Non-static variable from static context?

    Hi,
    I've created a program using swing components
    and I've set up a addActionListener to a button,
    button.addActionListener(this);
    when try and compile I get the following error:
    non-static variable this cannot be referenced from a
    static context
    button.addActionListener(this);
    I've checked site and my notes I don't seem to have
    done anything different from programs that have compiled
    in the past.
    I'm currently doing a programming course so I'm fairly
    new to Java, try not to get to advanced on me :)
    Thx in advance for any help.
    Chris

    Well what is declared static? If I remeber right this error means that you have a static method that is trying to access data it does not have access to. Static methods cannot access data that is intance data because they do not exist in the instance (not 100% sure about this but I believe it is true, at the very least I know they do not have access to any non-static data). Post some more of your code like where you declare this (like class def) and where you set up the button.

  • Non static  variable in static context

    import java.util.Scanner;
    public class project4_5 {
         int die1, die2;
         int comptotal = 0, playertotal = 0, turntotal = 0;
         int turn, comprun = 0;
         String playername;
         String action = ("R");
         Scanner scan = new Scanner(System.in);
            public static void main (String[] args)
            PairOfDice mydie = new PairOfDice();
         System.out.println("!!!!!!PIG!!!!!!");
         System.out.println();
         System.out.println("Enter your name! ");
         playername = scan.nextLine();
         while(playertotal>100 && comptotal>100){
         while(action.equalsIgnoreCase("R")){
                   System.out.println(playername+" roll or pass the die (R/P) ");
                   action = scan.nextLine();
                   if(action.equalsIgnoreCase("P"))
                        break;
                   mydie.roll();
                   die1 = mydie.getFace1();
                   die2 = mydie.getFace2();
                   System.out.println("You rolled a "+die1+" and a "+ die2);
                   if(die1==1||die2==1){
                        turntotal = 0;
                        System.out.println("You rolled a 1, you lose your points"
                        +" for this turn.");
                        break;
                   else if(die1==1&&die2=1){
                        playertotal = 0;
                        System.out.println("You rolled snake eyes, all points have"
                        + " been lost.");
                        break;
                   else
                   turntotal= turntotal+die1+die2;
                   System.out.println("Would you like to roll or pass? (R/P)");
                           if(action.equalsIgnoreCase("P")){
                                playertotal = playertotal+turntotal;
                                turntotal = 0;
                   while(turntotal<=20||turns!=run){
                   turn = (int) (Math.random() * 5 + 1);
                   mydie.roll();
                   die1 = mydie.getFace1();
                   die2 = mydie.getFace2();
                   System.out.println("Computer rolled a "+die1+
                   " and a "+ die2);
                   if(die1==1||die2==1){
                        turntotal = 0;
                        System.out.println("Computer rolled a 1 he loses hi points"
                        +" for this turn.");
                        break;
                   else if(die1==1&&die2=1){
                        playertotal = 0;
                        System.out.println("Computer rolled snake eyes, his points have"
                        + " been lost.");
                        break;
                   else
                   turntotal= turntotal+die1+die2;
                   comprun++;
                   turntotal = 0;
       }here is code for a dice game i made...and when i compile it practically every variable gets an error saying non-static variable can not be referenced from a static context....anyone kno what this means or how i go about fixing it...i think it has something to do with assigning the return variable from my getFace method to die1 and die 2...idk how to fix it tho
    if u need it my die class is below
    public class PairOfDice
         int faceValue1, faceValue2;
         public PairOfDice()
              faceValue1 = 1;
              faceValue2 = 1;
         public void roll()
              faceValue1 = (int) (Math.random() * 6 + 1);
              faceValue2 = (int) (Math.random() * 6 + 1);
         public int getFace1 ()
              return faceValue1;
         public int getFace2 ()
              return faceValue2;
         

    It means what it says -- that you're trying to use a non-static thing (like a method or a field) from a static thing (like your main method).
    You can either make everything static (which isn't great -- it flies in the face of object-oriented programming) or instantiate an object.
    If you want to do the latter, then try this: make your main method instantiate a method, and run it, like this:
    public static void main(String[] argv) {
        project4_5 game = new project4_5();
        game.play();
    }Then create a method called play:
    public void play() {
      // put everything that's currently in main() in here
    }See if that fixes it for you.

  • Non static variable errors

    I have been working on this file for 4 days now and I can't get past these errors.
    Here's the whole project:
    package toysmanager;
    public class ToysManager {
    //Method ToysManager
    public ToysManager() {
    //Method main
    public static void main(String[] args) {
    ToddlerToy Train1 = new ToddlerToy();
    ToddlerToy Train2 = new ToddlerToy();
    ToddlerToy Train3 = new ToddlerToy();
    System.out.print("This is an object of type ToysManager");
    Train1.PrintProductID();
    Train2.PrintProductID();
    Train3.PrintProductID();
    public class ToddlerToy{
    private int ProductID = 0;
    private String ProductName = "";
    private float ProductPrice = 0;
    public ToddlerToy(int id,String name, float price){
    ProductID = id;
    ProductName = name;
    ProductPrice = price;
    //Method PrintProductID
    public int PrintProductID(){
    System.out.print("This method is PrintProductID in the class ToddlerToy");
    System.out.print("Product ID is:" + ProductID);
    return ProductID;
    public String PrintProductName(){
    System.out.print("This method is PrintProductName in the class ToddlerToy");
    System.out.print("Product Name:" + ProductName);
    return ProductName;
    public float PrintProductPrice(){
    System.out.print("This method is PrintProductPrice in the class ToddlerToy");
    System.out.print("Product Price: $" + ProductPrice);
    return ProductPrice;
    And here are the errors:
    "ToysManager.java": non-static variable this cannot be referenced from a static context at line 9, column 29
    "ToysManager.java": ToddlerToy(int,java.lang.String,float) in toysmanager.ToysManager.ToddlerToy cannot be applied to () at line 9, column 29
    "ToysManager.java": non-static variable this cannot be referenced from a static context at line 10, column 29
    "ToysManager.java": ToddlerToy(int,java.lang.String,float) in toysmanager.ToysManager.ToddlerToy cannot be applied to () at line 10, column 29
    "ToysManager.java": non-static variable this cannot be referenced from a static context at line 11, column 29
    "ToysManager.java": ToddlerToy(int,java.lang.String,float) in toysmanager.ToysManager.ToddlerToy cannot be applied to () at line 11, column 29
    Any help would be appreciated as I am plainly not understanding this even with a book.

    Annie:
    Could you help me understand the original ToyManager instructions more please? Not asking you to do the work for me I just do not understand exactly what they want me to do...
    Assignment:
    After you install JCreator, write a Java program, with a single class called ToysManager. The main method should print the name of the class, for example: "This is an object of type ToysManager."
    (Hint: the process is very similar to the "Hello World!" program.)
    Please add file (.java)
    Group Portion:
    Deliverables:  two *.java files
    As a group, add a second class called ToddlerToy to your ToysManager project.
    Here are  the requirements for the ToddlerToy:
        * The class ToddlerToy is public and has a default constructor.
        * It  has  one private attribute called  ProductID (of type int).
        * It has two public  methods called  SetProductId() and PrintProductId().
        * The method SetProductId() assigns a value to the attribute ProductId. For now, the value is hard-coded.
        * The method  PrintProductId prints the value of the attribute ProductId.
        * The class ToddlerToy has no main() method.  In Java, there is only one main method for the entire program. In this case, the main method is in the ToysManager class.
    Here are the requirements for the main method of the ToysManager class:
        * Create an object called Train1 of  class  type ToddlerToy, using the default  constructor.
        * Call the methods SetProductId() and PrintProductId() to set then print the the value of ProductId.
        * The first statement  in each method should print the name of the method, for example:  "This is method <method name> in class <class name>". This should help you trace the execution of your program. Feel free to comment out the print statement.
        * On the Small Group Discussion Board, discuss your understanding of the concepts of class, object, constructor, method, and attribute.
        * Give one example of a class (giving its name, attributes, and methods)  that could be part of the shipping application.ANY help with this at all is greatly appreciated...a friend of mine found your post and used it to give me code snippets for help and I had no idea. Nearly got me in deep water...redoing the assignment but personally I find the next two assignments much easier to understand than this one. The instructions are confusing to me...can you point me in the right direction?

  • Non-static variable aceYears cannot be referenced from a static context

    This is my error...
    investment.java:53: non-static variable aceYears cannot be referenced from a static context
    lwInvest.numberAceYears(aceYears);
    ^
    This is my code...
    public static void main (String[] args)
    investment.Invest.numberAceYears(aceYears);
    and more code
    String termInvested = JOptionPane.showInputDialog
    ("Please enter the amount of years to invest your investment.");
    int intTermInvested = Integer.parseInt(termInvested);
    and yet more code..
    public void numberAceYears (int aceYears)
    for (int aY = 5 ; aY <= aceYears; aY++)
    double aceInterest = aceCoBalance * aceCoRate /100;
    aceCoBalance = aceCoBalance + aceInterest;
    aceYears = aceYears + aY;
    Suggestions?

    Short version: Either make the variable in question static, or create an instance of your class and use that to access it. Either one will work, but one probably suits your design better. It's up to you to figure out which one.
    For details, see the relevant section of your favorite Java book or tutorial, or poke around here:
    http://www.google.com/search?q=java+non+static+variable+cannot+be+referenced+from+a+static+context

  • 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 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."

  • Cannot be referenced from a static context

    im trying to link my user interface to the Game class to jump,
    i get the error - non static method jump() cannot be referenced from a static context
    private void jButton1_actionPerformed(ActionEvent e)
              System.out.println("\njButton1_actionPerformed(ActionEvent e) called.");
              // code
    Game.jump();
    any ideas? thanks

    ah, it works if i change jump() to static
    i was now wondering how to make the user interface
    work with this ethod in the Game() class
    private void goRoom(Command command)
    if(!command.hasSecondWord()) {
    // if there is no second word, we don't know where to go...
    System.out.println("Go where?");
    return;
    String direction = command.getSecondWord();
    // Try to leave current room.
    Room nextRoom = currentRoom.getExit(direction);
    if (nextRoom == null)
    System.out.println("There is no door!");
    else {
    currentRoom = nextRoom;
    System.out.println(currentRoom.getLongDescription());
    i was thinking something like
    private void jButton1_actionPerformed(ActionEvent e)
    // code
    Game.goRoom(Command north);
    it doesnt seem to like that though.. :s

Maybe you are looking for