Solved

checking user input value

Posted on 2003-11-24
21
313 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
  • 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
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
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 16

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 16

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 16

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 16

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 16

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 16

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

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
eclipse shortcuts 9 62
diffSum example 4 50
more than one jdk and one jre 1 50
Adding multiple JVM environments to RedHat 6 7 47
After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

839 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