• Post Reply Bookmark Topic Watch Topic
  • New Topic

how do I test if an object exists yet?  RSS feed

 
Kate Sky
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a class Square with several different constructors - one takes an int, another takes a double, and I have a no arg constructor Square() too .
Another class Test uses the input variable to its main() method ( String[] args ) to construct a Square.
So, I'm trying
s = new Square(Integer.parseInt(args[0]));
first. If that doesn't work, it will throw a NumberFormatException, which I handle by going on to try ...
s = new Square(Double.parseDouble(args[0]));
Well, if it's not a double either, then I'll get a NumberFormatException and no Square() constructor called.
So, right at the end, I want to say
if (s doesn't exist yet) {s = new Square() }
but it's that 'if S doesn't yet exist' I can't figure out.
Thanks,
Kate
 
James Swan
Ranch Hand
Posts: 403
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Square s;
...
if (s == null) {
s = new Square(...);
}
 
Kate Sky
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yeah - that's what I thought. The compiler's objecting because "variable s might not have been initialized" at the
bit.
Which looks like a bit of a circular argument on its part
 
James Swan
Ranch Hand
Posts: 403
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Square s = null;
...
if (s == null) {
s = new Square(...)
}
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
kate in the sky,
Welcome to JavaRanch!
We ain't got many rules 'round these parts, but we do got one. Please change your display name to comply with The JavaRanch Naming Policy.
Thanks Pardner! Hope to see you 'round the Ranch!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!