Circuit Negma

C++, C, VB.NET, PCB, Electronics, Circuit Design

Java Applet: How to check if the input is a valid integer?

Posted by Circuit Negma on March 3, 2006


Lets say that we need the interactive user to enter a valid integer only.

The following code will check the validity of the given input.

385 // <editor-fold defaultstate=”collapsed” desc=” Obtain File Numbers and Verify “>
386 this.Startnum = GetIntegerValid(this.jTextField3.getText(), this.jTextField3); // here we are calling GetIntegerValid(String s, jTextField textfield)
387 this.Endnum = GetIntegerValid(this.jTextField4.getText(), this.jTextField4); // method.
388 if(this.Startnum == 0) // Check if the results of above method are valid.
389 return;
390 else if (this.Endnum == 0)
391 return;
392
393 System.out.println(this.Startnum); // this line is used as a debuging method
394 System.out.println(this.Endnum); // this line is used as a debuging method
395 // </editor-fold>

429 private int GetIntegerValid(String s, javax.swing.JTextField textfield)
430 {
431 int i = 0;
432 try{
433 i = new Integer(s).intValue();
434 }
435 catch(NumberFormatException e)
436 {
437 System.out.println(e);
438 textfield.setBackground(Color.YELLOW);
439 textfield.setText(“Please Enter a Valid Number”);
440 }
441 return i;
442 }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: