Non-static method error message

why this error message? i'm new to Java.
Non-static method compare(java.lang.object,java.lang.Object) cannot be referenced from a static context at line 54.
Any assistance would be greatly appreciated. Thanks.
Calling Method;
private static void selectionSort(Object[] objectArray)
int min, temp;
for (int index = 0; index < objectArray.length-1; index++)
min = index;
int alen = objectArray.length;
for (int scan = index+1; scan < alen; scan++)
(Line 54) NameComparator.compare(objectArray[scan],objectArray[min]);
Invoked Class/Method:
import java.util.Comparator;
public class NameComparator implements Comparator {
private String object, object1, firstCompare, secondCompare;
// Constructors
public NameComparator()
firstCompare = object;
secondCompare = object1;
// Compare method
public int compare(Object object, Object object1)
int result = firstCompare.compareTo(secondCompare);
return result;
}

That message occurs when you attempt to call a regular class method from a static class method, which usually means that you've called a regular method from main(). Remember this is main:
public static void main( String[] args ) { . . . }The static keyword means that main() is part of the class, but not part of objects created from that class. The error message is really saying:
// You're trying to use a method that needs an object of this class type,
// but you don't have an object of this class type.I get this message often enough. It just means that I forgot to create an object, or that I forgot to use it when I called the method.
class SomeThing {
  public static void main( String[] args {
    doWhatever(); // wrong - requires a SomeThing object
    SomeThing st = new SomeThing(); // got a SomeThing now
    doWhatever(); // still wrong - only works for an object
    st.doWhatever(); // finally right!
  } // end main()
  SomeThing() { . . . } // constructor for SomeThings
  doWhatever() { . . . } // method that a SomeThing can perform
} // end of class SomeThing

Similar Messages

  • Non static method error

    How do i get the string "pin" into my prepared statement?
    String pin;
    public void setFrmPin (String value)
         { pin = value; }
        Class.forName("org.gjt.mm.mysql.Driver").newInstance();
          con = DriverManager.getConnection("jdbc:mysql://localhost:3306/jobprop?user=root&password=");
          if(!con.isClosed())
            System.out.println("Successfully connected to " +
              "MySQL server using TCP/IP...");
                           try
              sql = "INSERT INTO freehold_form_main(username)VALUES(?)";
              prep = con.prepareStatement(sql);
              prep.setString(1,pin);
              //prep.setString(2,"asas");
              prep.executeUpdate();
              catch(Exception m)
              System.out.print(m.getMessage());
        } catch(Exception e) {
          System.err.println("Exception: " + e.getMessage());
        } finally {
          try {
            if(con != null)
              con.close();
          } catch(SQLException e) {}
      }thanks in advance.

    prep.setString(1,pin);
    this doesn't work.
    when i try to compile it says
    C:\tomcat_5.5\webapps\jobprop\WEB-INF\classes\savedata>javac saveData.java
    saveData.java:526: non-static variable pin cannot be referenced from a static co
    ntext
                    prep.setString(1,pin);
                                     ^
    1 error

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

  • Error: Cannot make a static reference to the non-static method

    Below is a java code. I attempt to call method1 and method2 and I got this error:
    Cannot make a static reference to the non-static method but If I add the keyword static in front of my method1 and method2 then I would be freely call the methods with no error!
    Anyone has an idea about such error? and I wrote all code in the same one file.
    public class Lab1 {
         public static void main(String[] args) {
              method1(); //error
         public  void method1 ()
         public  void method2 ()
    }

    See the Search Forums at the left of the screen?
    If you had searched with "Cannot make a static reference to the non-static method"
    http://search.sun.com/search/onesearch/index.jsp?qt=Cannot+make+a+static+reference+to+the+non-static+method+&rfsubcat=siteforumid%3Ajava54&col=developer-forums
    you would have the answer. Almost every question you will ask has already been asked and answered.

  • 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 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 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 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 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 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 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);
    }

  • How do I identify which is static and which is non static method?

    I have a question which is how can i justify which is static and which is non static method in a program? I need to explain why ? I think it the version 2 which is static. I can only said that it using using a reference. But am I correct or ?? Please advise....
    if I have the following :
    class Square
    private double side;
    public Square(double side)
    { this.side = side;
    public double findAreaVersion1()
    { return side * side;
    public double findAreaVersion2(Square sq)
    { return sq.side * sq.side;
    public void setSide(double s)
    { side = s;
    public double getSide()
    { return side;
    } //class Square
    Message was edited by:
    SummerCool

    I have a question which is how can i justify which is
    static and which is non static method in a program? I
    need to explain why ? I think it the version 2 which
    is static. I can only said that it using using a
    reference. But am I correct or ?? Please advise....If I am reading this correctly, that you think that your version 2 is a static method, then you are wrong and need to review your java textbook on static vs non-static functions and variables.

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

  • Painting jpeg in java application: non-static method ... static context

    Hi!
    I simply want to show a jpeg within a java application. Showing the jpeg in an applet is no problem (see code below). But I have difficulties to translate this code to a java application. No matter what I try to load the jpeg, I end up with the following error:
    non-static method createImage() cannot be referenced from a static context
    How can I surround it? Thanx in advance for your help!
    Working applet
    import java.applet.*;
    import java.awt.*;
    public class shJpAp extends javax.swing.JApplet {
    Image pic;
    /** Creates a new instance of shJpAp */
    public shJpAp() {
    public void init() {
    pic=getImage(getCodeBase(), "lemmer.jpg");
    prepareImage(pic,this);
    public void paint (Graphics g) {
    g.drawImage(pic,0,0,this);
    Application
    import java.awt.*;
    public class shJp extends javax.swing.JFrame {
    Image pic;
    /** Creates new form shJp */
    public shJp() {
    initComponents();
    //pic = java.awt.Toolkit.getImage("lemmer.jpg");
    ---> pic = java.awt.Toolkit.createImage("lemmer.jpg");
    ---> prepareImage(pic, this);
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    private void initComponents() {
    addWindowListener(new java.awt.event.WindowAdapter() {
    public void windowClosing(java.awt.event.WindowEvent evt) {
    exitForm(evt);
    pack();
    /** Exit the Application */
    private void exitForm(java.awt.event.WindowEvent evt) {
    System.exit(0);
    * @param args the command line arguments
    public static void main(String args[]) {
    new shJp().show();
    // Variables declaration - do not modify
    // End of variables declaration
    public void paint( Graphics g) {
    g.drawImage(pic, 0,0,this);
    }

    Hi,
    just want to add a solution I found in some textbook (see code below). I hate finding every possible question in the internet, but seldom fitting answers.....
    But again, one little thing pushed me close to my first heart attack: The code below works well when executed by foot (...java showPic...). In the NetBeans 3.6 the frame refuses to show the pic!
    I am looking for an appropiate forum - but if anyone of you can help, it would be very nice ;-)
    import java.awt.*;
    import java.awt.event.*;
    public class showPic extends Frame {
    Image pic;
    public showPic() {
    addWindowListener( new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    pic = getToolkit().getImage("lemmer.jpg");
    setSize(200,100);
    setVisible(true);
    public void paint(Graphics g) {
    if (pic != null) {
    g.drawImage(pic,60,20,this);
    public static void main( String[] args ) {
    new showPic();
    }

Maybe you are looking for

  • How to CATCH error from call to standard SAP Function Module

    Please, is it possible to catch the following error with the TRY CATCH ENDTRY construct? From a custom program, am calling CS_BOM_EXPL_MAT_V2. Several nested calls in, Form STL_DATEN_HOLEN (LCSS4F1I) calls FM CS_ALT_SELECT_MAT.  However, that call is

  • Send a XML file using the mail adapter

    HI , I have to send an incoming xml message as a attachment in the mail using mail adapter . how can I achieve this . Thanks Nikhil

  • Short coming in BAPI for saving Document Long Text

    Hello Experts, I would be thankful to you if anyone of you offer a solution to the problem below. I have found that the tables parameter LONGTEXTS of function BAPI_DOCUMENT_CHANGE/CHANGE2/CREATE/CREATE2 (structure BAPI_DOC_TEXT) could include the fie

  • Oracle Service Bus business service - How to disable XML content check.

    Hi All, Dear Experts I have the necessity to disable the check on the XML content when message is forwarded to external system by on Oracle Service Bus Business Service to avoid that the XML content as string that I inserted in message is wrapped wit

  • ALE error - variant LOGSYS does not exist?

    In trying to setup ALE within SAP (ECC 5.0) to send a material master IDOC from the ERP to XI.  I followed the ALE Quick Start guide and several other resources on the net including IDOC Cookbook and others.  When I try to select transaction BD10 (Se