Solved

checking user input value

Posted on 2003-11-24
21
308 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
 
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
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
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

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
noX challenge 17 76
wordappend challenge 8 85
Which is the latest version of Apache Tomcatl 3 35
recursion example 16 70
For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
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 explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

760 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

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now