how to instance a non-static method, that has a wired object and is from another file
I'm having trouble calling a non-static method from an another file. My main file is called jroff.java, and the other file (which has the two methods I need) is called linkedqueue.java
In linkedqueue.java I have the following code:
class linkedqueue <item_t> {
private class node{
item_t item;
node link;
}
private node front = null;
private node rear = null;
public boolean empty (){
return front == null;
}
public void insert (item_t any) {
node temp = new node();
t开发者_JS百科emp.item = any;
temp.link = null;
if(rear == null) front = temp;
else rear.link = temp;
rear = temp;
}
public item_t remove (){
item_t value;
if (empty ()) throw new NoSuchElementException ();
value = front.item;
front = front.link;
if(front == null) return null;
else return value;
}
}
this is how i'm trying to run insert in my main file:
for (String word: words) linkedqueue.insert(word);
I got the file name thing right, but how exactly do I make an instance of something like this? Here is where I use insert:
String value;
while(value != null){
value = linkedqueue.remove().toString();
remove returns a item_t, and i want that in a string. the last node will have a value of null, thats when the loop should stop.
Thanks for the help.
There is no such thing as calling a method from another file.
In Java you are defining classes and you can interact with the non-static methods of a class by creating an instance of this class with the new
keyword.
I highly recommend either reading Java in a Nutshell or doing the Java tutorial. It will make things a lot clearer.
There are a couple issues with this code:
The naming convention in Java is to have class names starting with a capital letter, and variables starting with a lowercase. This is important here because it might be a source of confusion for you.
linkedqueue.insert(word);
looks like a legal command, but you are in fact trying to call a non-static method on aClass
object. This is not possible. You should create an instance of the class before trying this:linkedqueue lq = new linkedqueue();
and then perform all of your actions on
lq
.Based on your own spec, the following will throw a
NullPointerException
by design, if it ever got past a few issues:
String value; while(value != null){ value = linkedqueue.remove().toString(); }
- a variable in a method needs to be initialized before it is used.
- if it were initialized to
null
, your body of yourwhile
will never execute. Consider ado{}while()
instead.
精彩评论