Solved

checking user input value

Posted on 2003-11-24
21
315 Views
Last Modified: 2010-03-31
How am I to make sure the user keyin only integers & not string values like "abc"?

0
Comment
Question by:zhobi
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 5
  • 4
  • +1
21 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 9812195
int i = 0;
try {
    i = Integer.parseInt(value);
}
catch(NumberFormatExcpetion e) {
    System.err.println("only numbers allowed!");
}
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 9812201
>>
catch(NumberFormatExcpetion e) {

=

catch(NumberFormatException e) {
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 9812492
If you want them to be able to enter decimals too:

double i = 0;
try {
    i = Double.parseDoublevalue);
}
catch(NumberFormatException e) {
    System.err.println("only numbers allowed!");
}

0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 86

Accepted Solution

by:
CEHJ earned 63 total points
ID: 9812494
If you want them to be able to enter decimals too:

double i = 0;
try {
    i = Double.parseDouble(value);
}
catch(NumberFormatException e) {
    System.err.println("only numbers allowed!");
}

0
 
LVL 17

Expert Comment

by:krakatoa
ID: 9812690
.................................................................................................................
   public class kA extends KeyAdapter {
       public kA() {
           super();
       }


public void keyTyped(KeyEvent e){

if((!(e.getKeyChar()>='0'&&e.getKeyChar()<='9'))&&e.getKeyChar()!=','){e.consume();}

}


public void keyPressed(KeyEvent e){

   if(e.isControlDown()==true){e.consume();}

}

}//.................................................................................................................


Allowance for a ",", in case you wanted to input anything over 999 with formatting, or you are not in a country where the "." is used for decimal delimiter. You can add in the "." yourself (or anything else you like really) - or take it out if you dont want it!
0
 
LVL 2

Expert Comment

by:anthony_castillon
ID: 9813685
Instead of using an ordinary JTextField, you may want to create a class implementing javax.swing.text.Document.  Better yet, create a subclass of javax.swing.text.PlainDocument and override the insertString( ) method.  I've done this before but I don't have a sample code right now coz it's in my other computer.  However, it's good so that you can make sure that you only enter numeric values (including '.'), and not allow non-numeric inputs.

Anthony
0
 
LVL 17

Expert Comment

by:krakatoa
ID: 9814587
>> but I don't have a sample code right now coz it's in my other computer ..

that's useful then.
0
 
LVL 2

Assisted Solution

by:anthony_castillon
anthony_castillon earned 62 total points
ID: 9820657
With this, I hope you can now give me the points.

===========
import javax.swing.text.*;
import javax.swing.*;

/**
 *  This class serves as a model for documents (including textfields, textareas) requiring
 *  numbers-only entries.
 *
 */
public class NumericFormatDocument extends PlainDocument {
   
   
    /** Size limit of the Document object, including any periods representing the decimal point.
     */    
    private int size;
   
    /** Indicates whether the Document object can accept decimal points
     */    
    private boolean allowDecimals;
   
    private int periods = 0;
   
    /** Default no-arg constructor.  The size and allowDecimals instance variables can be set via the setSize() and setAllowDecimals() methods.
     */    
    public NumericFormatDocument() {
        super();
    }
   
    /** Creates an instance of NumericFormatDocument using size argument with a allowDecimals variable set to true.
     */    
    public NumericFormatDocument(int size) {
        this(size, true);
    }
   
   
    /** Creates an instance of NumericFormatDocument with the arguments used to set values for the variables size and allowDecimals, respectively.
     */    
    public NumericFormatDocument(int size, boolean allowDecimals){
        if (size < 0 ) size = 0;
        this.size = size;
        this.allowDecimals = allowDecimals;
    }
   
    /** Sets the maximum size of the Document object
     */    
    public void setSize (int size){
        this.size = size;
    }
   
    /** Sets whether decimal points can be added to the Document.
     */    
    public void setAllowDecimals (boolean allowDecimals){
        this.allowDecimals = allowDecimals;
    }
   
   
    /** Returns the maximum size for the Document object
     */    
    public int getSize(){
        return size;
    }
   
    /** Returns flag whether decimal points can be included in the Document
     */    
    public boolean getAllowDecimals(){
        return allowDecimals;
    }
   
    /** Overridden method from the PlainDocument superclass
     */    
    public void insertString(int offset, String s, AttributeSet attributes) throws BadLocationException {
       

       
        if (size > 0 && (getLength()+1) >size) {
            return;
        }
       
        if (s == null) return;
       
        int length = s.length();
       
        for (int i = 0 ; i < length; i++) {
            char character = s.charAt(i);
           

            if (allowDecimals){
                if (character == '.'){
                    if (periods > 0){
                        return;
                    } else {
                        periods++;
                        continue;
                    }
                }
            }
           
            if (!Character.isDigit(character)) {
                return;
            }
        }
       
       
        super.insertString(offset, s, attributes);
       
    }
}
0
 
LVL 2

Expert Comment

by:anthony_castillon
ID: 9820719
By the way, you can now use the class above when you create an instance of JTextField:

JTextField tf = new JTextField(new NumericFormatDocument(), "", 20);

This will give you a textfield with size 20 and can only accept numeric inputs.
0
 
LVL 17

Expert Comment

by:krakatoa
ID: 9820786
That's snappy code. About ten times longer than mine and quite a bit heavier.
0
 
LVL 92

Expert Comment

by:objects
ID: 9822639
anthony_castillon code is the best way to ensure only numbers can be entered.
0
 
LVL 17

Expert Comment

by:krakatoa
ID: 9823294
>> anthony_castillon code is the best way to ensure only numbers can be entered. ...

Well I dont see how this can be the case, and in any event the choice is for the questioner to make. :)
0
 
LVL 17

Expert Comment

by:krakatoa
ID: 9823397
And of course the fact that it wont even compile due to the innacuracies doesnt help matters much either. :@)
0
 
LVL 2

Expert Comment

by:anthony_castillon
ID: 9824365
I wrote the code early last year.  I'm not sure if the Swing API had major changes during that time through now.  If it doesn't compile, maybe a few tweaks should do the trick.
0
 
LVL 92

Expert Comment

by:objects
ID: 9827372
compiles fine here
0
 
LVL 17

Expert Comment

by:krakatoa
ID: 9827686
My solution is actually total cack, so I would just ignore it completely; it doesnt work for me, never has, and probably wont even compile on a normal computer (mine is driven by gas and solar panels). In fact, looking at the code again, it falls so far short of the mark that it almost qualifies me for instant demotion to the leading EE anti-expert. In fact, it isnt even written in Java, it's some Middle Earth tongue that I made up in the shower one day. There you are.

Anyone for Rugby?

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 11657299
>>I would appreciate any comments by the experts that would help me in making a recommendation.

Well of course the solution i suggested would work fine ;-)
0
 
LVL 92

Expert Comment

by:objects
ID: 11662726
points to anthony_castillon
0

Featured Post

Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…

690 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question