File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Variables in a program" Watch "Variables in a program" New topic

Variables in a program

Alex Mun

Joined: Oct 05, 2004
Posts: 14

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


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

public Nodo()
Nodo n=new Nodo();

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

if (
if (!=null)

public static void main(String args[])
Nodo nuevo=new Nodo();

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?

Joel McNary

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 " = 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:
subject: Variables in a program
It's not a secret anymore!