• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 318
  • Last Modified:

checking user input value

How am I to make sure the user keyin only integers & not string values like "abc"?

0
zhobi
Asked:
zhobi
  • 6
  • 5
  • 4
  • +1
2 Solutions
 
CEHJCommented:
int i = 0;
try {
    i = Integer.parseInt(value);
}
catch(NumberFormatExcpetion e) {
    System.err.println("only numbers allowed!");
}
0
 
CEHJCommented:
>>
catch(NumberFormatExcpetion e) {

=

catch(NumberFormatException e) {
0
 
CEHJCommented:
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
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
CEHJCommented:
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
 
krakatoaCommented:
.................................................................................................................
   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
 
anthony_castillonCommented:
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
 
krakatoaCommented:
>> but I don't have a sample code right now coz it's in my other computer ..

that's useful then.
0
 
anthony_castillonCommented:
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
 
anthony_castillonCommented:
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
 
krakatoaCommented:
That's snappy code. About ten times longer than mine and quite a bit heavier.
0
 
objectsCommented:
anthony_castillon code is the best way to ensure only numbers can be entered.
0
 
krakatoaCommented:
>> 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
 
krakatoaCommented:
And of course the fact that it wont even compile due to the innacuracies doesnt help matters much either. :@)
0
 
anthony_castillonCommented:
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
 
objectsCommented:
compiles fine here
0
 
krakatoaCommented:
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
 
CEHJCommented:
>>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
 
objectsCommented:
points to anthony_castillon
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

  • 6
  • 5
  • 4
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now