3

I would like to understand this once and for all.

With this please excuse the mass of code pasted below, but I do not want to leave out any details.

The only thing I changed is the URL loaded. But this is not causing the error.

I would like to call my function "readPosiitons". Easy solution, make it static. Real solution, I am not sure of.

Please help me to better understand how to solve this error in the correct way.

Thanks!!

            /*
             * To change this template, choose Tools | Templates
             * and open the template in the editor.
             */

            package PandL;

            import java.io.BufferedReader;
            import java.io.File;
            import java.io.IOException;
            import java.io.InputStreamReader;
            import java.net.MalformedURLException;
            import java.net.URL;
            import java.util.HashMap;
            import java.util.Scanner;
            import toolBox.Secretary;
            import toolBox.Secretary.positionObj;

            /**
             *
             * @author Jason
             *
             */
            public class GarageComm {
                public static void main(String[] args) throws MalformedURLException, IOException{
                    String retStr;
                    String startM;
                    String endM;
                    String myURL;
                    String[] Split1=null;
                    Integer lnCount;
                    HashMap hashPos=new HashMap();
                    hashPos= readPositions("holdingsBU.txt");//the error is here

                    myURL="http://myUrl?s=";

                    URL url = new URL(myURL);
                    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));



                    in.close();
                }

                public HashMap readPositions(String destFile){

                    HashMap<String, Secretary.positionObj> hashPositions=new HashMap<String,positionObj>();
                    Secretary mySecretary=new Secretary();
                    try{
                        File F=new File(destFile);
                        if(F.exists()){
                            System.out.println("File Exists: "+F.exists());
                            System.out.println(destFile);
                            Scanner sC= new Scanner(F);

                            while (sC.hasNext()){
                                String[] Splitter1;
                                Secretary.positionObj position=mySecretary.new positionObj();


                                Splitter1=sC.nextLine().split(",");
                                position.positionDate=Double.parseDouble(Splitter1[0]);
                                position.positionTicker=(Splitter1[1]);
                                position.positionOpen=Double.parseDouble(Splitter1[2]);
                                position.positionPrice=Double.parseDouble(Splitter1[3]);
                                position.positionSMA=Double.parseDouble(Splitter1[4]);
                                position.positionUpdated=Double.parseDouble(Splitter1[5]);
                                position.priceUpdated=Double.parseDouble(Splitter1[6]);
                                position.updateDate=Double.parseDouble(Splitter1[7]);


                                hashPositions.put(position.positionTicker.trim(), position);

                            }


                        }else{
                            System.out.println("File Created: "+ F.createNewFile());
                            System.out.println("----No previous positions----");
                        }

                    }catch (Exception E){
                        System.err.println(destFile + " does not exist.");
                        hashPositions.put("ERROR", null);
                        E.printStackTrace();
                    }
                    return hashPositions;
                }
            }
1
  • Are you asking why you have to declare it static? Commented May 12, 2011 at 2:46

5 Answers 5

2

Real solution? Don't put so much stuff in the main() method. That's for noobs.

Java's an object-oriented language. Put the logic inside methods associated with the GarageComm class. main() should do little more than instantiate an instance and call its methods.

Change it like this:

            GarageComm gc = new GarageComm();
            hashPos= gc.readPositions("holdingsBU.txt");//the error is here
Sign up to request clarification or add additional context in comments.

Comments

2

This is a typical mindbender for new Java programmers.

A static method does not belong to an object. A non-static method belongs to an object.

You use the main-method convention to have your program started, and it is required that that method must be static.

The trick to get from a static method to a non-static method, is that you must create an object so you can call the method on that. I.e. new GarageComm().readPositions(...). I just don't think you have to here, so it would be simpler to just mark readPositions as static too.

Comments

1

You need to make your function static:

public static HashMap readPositions(String destFile) {
...
}

Creating an instance of GarageComm would work too, but this is bad programming practice in Java, since that object has no state.

5 Comments

It's not a bad practice. It's just a badly done solution. Don't be a purist; make it work.
@duffymo What is the difference between bad practice and badly done solution? I don't get what you mean...
A bad practice is something that you'd advise someone who's a good programmer to pick up. This appears to be a person who is just learning how to code, because this should be an easy error to correct for anybody who knows Java. So my advice would be to just make it work, even if the object design isn't perfect. Design is a skill that you develop once you're comfortable with syntax. This person is not at that point yet.
@duffymo Ewww... I believe indicating a good practice to a newbie is the best way to support him. I have provided a solution to make it work before the advice. But ok, I guess we disagree here...
Some objects can (and should) be stateless, so we'll disagree on that. We don't disagree as much about how to help newbies as much as you seem to think. If you read my answer again you'll see that there are other takeaways: "Don't put so much stuff in the main() method" and "put the logic in the GarageComm class."
0

If a method is not static, then it must be called "on" an object. When calling a method from a non-static method, that object is implied -- it's the object the first method was called on. But when calling it from a static method, there is no implied object, so to call the method, you must supply an object:

GarageComm gc = new GarageComm();
hashPos= gc.readPositions("holdingsBU.txt");

Since GarageComm has no state of its own, there's no reason to create a GarageComm object, so it's just as well you mark the method static, so no object is required to call it.

Comments

0

It's a good idea in this case to make the method static. The other way is to use

  new GarageComm().readPositions("holdingsBU.txt")

instead.

So, why this error?

A static method can not call a non-static method in the same class. It sounds bizarre, but there is a reason for it. Consider this:

  • Non static methods may depend on the state of the objects, the instance variable to say.

  • Static methods can be called from out-side without instanciating

Now, if we allow static methods to play with non-static method (and non static variables), they might fail. So, it is a kind of prevention.

When should I consider making a method static?

Now, come to, why not make the method static?,

Very well, you should make a method static if it's functionality does not depend on the object's state.

If it just uses the passed parameters and some static stuffs (static variable, static methods) and returns (with/without a result, throwing exception anything), consider making it static method.


update: looked like this post confused a couple of people so updated the answer.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.