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

showInputDialog question  RSS feed

 
Dilip kumar
Ranch Hand
Posts: 360
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I'm trying to handle situation if users clicks on OK button without entering anything in input box. Wondering what's wrong with below code.
String seats = JOptionPane.showInputDialog(frame, "Please enter number of tickets :");
if ( seats == null ) return;
if(Integer.valueOf(seats).intValue()==0 | | seats.trim().length()==0) {
   JOptionPane.showMessageDialog(null, "Please enter valid number.", "Invaid Entry", JOptionPane.INFORMATION_MESSAGE );
  return;
}
Thanks
 
amit bargotra
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

use if(seat.equals(null)) or if (seat.equals("")) instead of if ( seats == null ) .
 
Brad Page
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks amit, I have been trying to figure my own problem out for 3 hours now. Do you know why it doesnt work the other way? ( with the ==)
 
Tamizh Selvan
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The "==" does not work because the showInputDialog method actually returns a string with 0 length when clicked ok button and not null.
Marcus
 
VIJAY Yadlapati
Ranch Hand
Posts: 175
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Don't use seats.equals(null) because if seats is null, it will throw NullPointerException.
I think you have to use
String seats = null;
int noOfSeats = 0;

seats = JOptionPane.showInputDialog(frame, "Please enter number of tickets :");
while(seats == null)
{

JOptionPane.showMessageDialog(
null,
"Please enter valid number.",
"Invaid Entry",
JOptionPane.INFORMATION_MESSAGE);
seats = JOptionPane.showInputDialog(frame, "Please enter number of tickets :");
try
{
noOfSeats = Integer.parseInt(seats);
}
catch(NumberFormatException nfe)
{
}

if(noOfSeats == 0)
{
seats = null;
}
}
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!