• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Constructor with a parameter

 
Urs Waefler
Ranch Hand
Posts: 77
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

This is my code:


public class A {

A(int d) {

System.out.println(d);

}

public static void main (String [] args) {

try {
int h = Integer.parseInt(args [0]);
}

catch (Exception e) {}

A x = new A(h);

}
}


It does not work. The compiler tells: cannot find symbol, symbol : variable h.

But the symbol is there? What is wrong.

Regards
Urs
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"h" is defined within the try block, inside the { } braces. It goes out of scope at the close brace, so the compiler can't "see" it any more. This is one bit of syntax that annoys me because it forces us to declare the variable before the try block, before we use it. This makes "h" visible to the try block and the catch block:

Now, is that really the logic you want or just an example of the compiler message? This only tries to create x if the argument causes an exception, right?
 
Peter Chase
Ranch Hand
Posts: 1970
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Surely, the simple solution to getting the scope you want for variable "h" is just to enclose the bit of code that uses "h" within some braces.
 
Urs Waefler
Ranch Hand
Posts: 77
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Now I have that code:


public class A {


A(int d) {

System.out.println(d);

}

public static void main (String [] args) {

int h;

try {
h = Integer.parseInt(args [0]);
}

catch (Exception e) {}

A x = new A(h);

}
}

Still it does not work. I do not understand the scope of h.
 
Svend Rost
Ranch Hand
Posts: 904
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Urs Waefler:
Now I have that code:





The above code should not give warning concerning h as far as I can tell(and if, it will state that h might not be initialized).

What I would do, if I were you - would be to solve the problem in small steps. For example, instead of initializing h with: Integer.parseInt just do something like: int h=10;

A variable, like h, lives - which means, that it is visible -in a scope. You can see a scope as the space between a { and the end tag }.

In your code, h's scope is the main method.

does this help you?

/Svend Rost
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic