I have been working with java just a little, but there is these small logic things that I seem to never understand and I'll give an example right away. I currently have this code:
class test {
public static void main(String[] args) {
ST<String, Integer> st;
st = new ST<String, Integer>();
for (int i = 0; !StdIn.isEmpty(); i++) {
String key = StdIn.readString();
st.put(key, i);
}
st.put("P", 5); // Put method
for (String s : st.keys()) {
StdOut.println(s + " " + st.get(s));
}
}
}
So what it does is that it creates a Symbol Table and inserts some data to it from a file provided. As you can see, I have a put method which inserts the value 5 on key "P". I want to create a method for this just for the sake of practice. So what I do is:
public static void addValue() {
st.put("P", 5);
}
and call that method instead of the "put" method in my code. However I can't compile this, since the method "addValue" doesn't know the variable st.
I then thought to put these two lines:
ST<String, Integer> st;
st = new ST<String, Integer>();
into the class constructor, but that didn't make it. Can someone please explain some logic behind this because theres clearly something I'm missing. How can I split this code into methods in a nice way just for the sake of practice? + If anyone knows of a good place to just read about logic like this, I'll be enourmously appreciated.
Thanks in advance.
addValue()to theSTclass. Then, you can simply callthis.put("P", 5);insideaddValue(..)instead ofst.put(..);- also, in the main method, you can doST.addValue();to invoke it - OR pass it as a variable like @DavidZhou indicates below :)public static void addValue(ST st), and call it likeaddValue(st)