?
Solved

checking user input value

Posted on 2003-11-24
21
Medium Priority
?
316 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
Get real performance insights from real users

Key features:
- Total Pages Views and Load times
- Top Pages Viewed and Load Times
- Real Time Site Page Build Performance
- Users’ Browser and Platform Performance
- Geographic User Breakdown
- And more

 
LVL 86

Accepted Solution

by:
CEHJ earned 252 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 248 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

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.

Question has a verified solution.

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

Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
Suggested Courses
Course of the Month13 days, 22 hours left to enroll

801 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