aspose file tools*
The moose likes Beginning Java and the fly likes Variables in a program Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Variables in a program" Watch "Variables in a program" New topic
Author

Variables in a program

Alex Mun
Greenhorn

Joined: Oct 05, 2004
Posts: 14
Hi,

I'm trying to compile a simple program but I can't due to one error. The program is the following:

import java.io.*;

class Nodo
{
private Object elemento;
private Nodo top,aux,fin;

public Nodo()
{
Nodo n=new Nodo();
n.elemento=null;
n.top=null;
n.fin=null;
n.aux=null;
}

public void push(Object e)
{
Nodo temp=new Nodo();

temp.elemento=e;
if (n.top==null)
{
n.top=n;
n.aux=n;
}
if (n.top!=null)
{
temp.elemento=e;
temp.fin=top;
top=temp;
}
}

public static void main(String args[])
{
Nodo nuevo=new Nodo();
nuevo.push(1);
}
}

After compiling the program I can display the following error:

Undefined variable or class name: n

This error appears me in the Push function and I don't know how to solve it.

Any ideas?

Thanks.
Joel McNary
Bartender

Joined: Aug 20, 2001
Posts: 1824

Where is n defined?

Currently, n is defined in your constructor. The problem is, when the constructor ends, n goes away (we call that, "going out of scope").

So, you have a few ways to solve this problem.

First, you can declare n in your push method. Keep in mind that this n might (and, in this case, would) reference a different object than the n declared in your constructor.

Second, you can declare n as a member variable, just as top, aux, and fin are.

Lastly, you can get rid on n altogether. The object referenced by n in your constructor is never used outside your constructor. Judging from how you are trying to use "n," it seems likely to me that you want to use the keyword "this" instead. "this" refers to the current object, which seems to be what you are trying.
(Note that you are using "this" implicitly in the line that says "top = temp;" you could also say "this.top = temp;" with no problem.")


Piscis Babelis est parvus, flavus, et hiridicus, et est probabiliter insolitissima raritas in toto mundo.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Variables in a program