Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Te4sting for uninitialised variables  RSS feed

 
David Eilloc
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi there,
I need to test for a session variable and display one bit of code if it has been initialised but another if it has not.
I have tried the obvious ones ala
if ((session.getValue("account_type").equals("Both") || session.getValue("account_type").equals("International Access"))) {
out.println("<input type=\"checkbox\" name=\"intAccess\" value=\"International Access\" checked=\"checked\">");
} else {
out.println("<input type=\"checkbox\" name=\"intAccess\" value=\"International Access\">");
}
But the same prob keeps coming up.
How do you test to see if a variable is there!!!
In Javascript it is aas simple as
if (variableName) {
//do code
}
How do you do a similar thing in Java
Cheers
David
 
David Eilloc
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
BTW just in case, keep getting aNullPointerException and I am a complete Java novice....
 
Roy Ben Ami
Ranch Hand
Posts: 732
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
just use an if first to check if it isnt null.
like this
if(session.getValue("account_type")!=null)
{
//here put the rest of yoyr code.

btw, if u r using servlet API 2.2 or 2.3 u should replace the getValue() with the getAttribute() method.
 
David Eilloc
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Roy Ben Ami,
thanks for the speedy reply, but I still seem to be getting nullpointerexception's .....
will try a few things out and post again...
david eilLOC
 
Kyle Brown
author
Ranch Hand
Posts: 3892
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Simplicity Rules! Don't try to do more than one thing on one line and your code will be much cleaner.
String foo = session.getValue("Foo");
if (foo != null) {
if (foo.equals("MyValue")) {
// do the myValue thing
} else {
// do the some other value thing
}
} else {
// print out some horrid error message
// about the session not being right
}
Kyle
 
David Eilloc
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Kyle,
That is the way that I ended up doing it but I felt a little uncomnfortable with it....
Is it cool....
david eilLOC
 
David Eilloc
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
PS good code advice as well kyle, will take it to heart!
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!