• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Variables in a program

 
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Bartender
Posts: 1844
Eclipse IDE Ruby Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.")
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic