Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Variables in a program

 
Alex Mun
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1840
Eclipse IDE Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.")
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic