I created a java program that will convert decimal to binary and vice versa. I don't have any problems with my decimal to binary. But when I coded my binary to decimal I get the following errors:
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:470)
at java.lang.Integer.parseInt(Integer.java:499)
at converter.actionPerformed(converter.java:42)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2028)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2351)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6382)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3275)
at java.awt.Component.processEvent(Component.java:6147)
at java.awt.Container.processEvent(Container.java:2083)
at java.awt.Component.dispatchEventImpl(Component.java:4744)
at java.awt.Container.dispatchEventImpl(Container.java:2141)
at java.awt.Component.dispatchEvent(Component.java:4572)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4619)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4280)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4210)
at java.awt.Container.dispatchEventImpl(Container.java:2127)
at java.awt.Window.dispatchEventImpl(Window.java:2489)
at java.awt.Component.dispatchEvent(Component.java:4572)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:704)
at java.awt.EventQueue.access$400(EventQueue.java:82)
at java.awt.EventQueue$2.run(EventQueue.java:663)
at java.awt.EventQueue$2.run(EventQueue.java:661)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:98)
at java.awt.EventQueue$3.run(EventQueue.java:677)
at java.awt.EventQueue$3.run(EventQueue.java:675)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:674)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:296)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:211)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:196)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:188)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
Here is my code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class converter extends JFrame implements ActionListener {
JTextField txt1;
JTextField txt2;
JLabel lbl1;
JLabel lbl2;
JButton b1;
JButton b2;
public converter(){
Container c = getContentPane();
JPanel jp = new JPanel();
c.add(jp);
jp.add(lbl1=new JLabel("Decimal: "));
jp.add(txt1=new JTextField(10));
jp.add(lbl2=new JLabel("Binary: "));
jp.add(txt2=new JTextField(10));
jp.add(b1=new JButton("Convert"));
jp.add(b2=new JButton("Clear"));
b1.addActionListener(this);
b2.addActionListener(this);
}
public static void main(String[] args) {
converter cvt = new converter();
cvt.setResizable(false);
cvt.setVisible(true);
cvt.setSize(250,150);
cvt.setTitle("Decimal - Binary Converter");
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String num = txt1.getText();
int i = Integer.parseInt(num);
if(txt1 != null && e.getSource() == b1){
String z = Integer.toBinaryString(i);
txt2.setText(z);
}
else if(e.getSource() == b2){
txt1.setText("");
txt2.setText("");
}
else if(txt2 != null && e.getSource() == b1){
int x = Integer.parseInt(txt2.getText().trim(), 2);
txt1.setText(""+x);
}
}
}
Can you point out what is wrong? And what can be its solution.
You don't have any bounds checking in your code. Aka, you have two text inputs and one 'Convert' function, but the function is applicable for all the following combinations:
Decimal input and Binary input are both given
Decimal input and Binary input are both omitted
Decimal input is given, Binary input is omitted
Decimal input is omitted, Binary input is given
You need to decide what to do in all four cases, and then proceed with your parse appropriately. Three out of four of these cases are pretty straightforward to deal with - leaving you with having to make a decision about what to do when a user fills in both the Decimal and Binary input fields then hits Convert (I would recommend showing an error dialog in that case).
As it stands, you are parsing your Decimal input field in all cases, and when its left blank this translates to:
Integer.parseInt("")
Which throws a NumberFormatException, as expected.
I would handle your four possible scenarios something like this:
public static boolean isEmpty(final String str) {
return (str == null || str.trim().equals(""));
}
final String decimalInput = text1.getText();
final String binaryInput = text2.getText();
if(! isEmpty(decimalInput)) {
if( ! isEmpty(binaryInput)) {
// Decimal input and Binary input are both given, show error
} else {
// Decimal input is given, Binary input is omitted, convert to binary
}
} else {
if( isEmpty(binaryInput)) {
// Decimal input and Binary input are both omitted, show error
} else {
// Decimal input is omitted, Binary input is given, convert to decimal
}
}
Check txt1 and txt2 value if it's a number or not.
The first line of the trace shows that there is an error thrown when your program tries to convert an empty string ("") to an int. If you look further down the trace (on line 5), the error occurs in the actionPerformed method. Particularly, the lines:
String num = txt1.getText();
int i = Integer.parseInt(num);
You could solve this problems by first checking if the string is not empty with:
if (num.length() < 1)
// tell user they must enter a number
A few things jump to mind.
You could trap the exception and display a message telling the user that the value they entered is invalid. You should also trim the result from the field just to be sure.
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
try {
String num = txt1.getText().trim(); // <-- Trim the incoming value
int i = Integer.parseInt(num);
if(txt1 != null && e.getSource() == b1){
String z = Integer.toBinaryString(i);
txt2.setText(z);
}
else if(e.getSource() == b2){
txt1.setText("");
txt2.setText("");
}
// I'm not sure if this a logic error or not, but txt2 is text field...
// Did you think it was the text from the field??
else if(txt2 != null && e.getSource() == b1){
int x = Integer.parseInt(txt2.getText().trim(), 2);
txt1.setText(""+x);
}
} catch (NumberFormatException exp) {
// Display message...
}
}
The other is to use a DocumentFilter to prevent the user from entering any values that are invalid for the fields.
Check out Text Component Features and examples
Updated
You also have some logic errors...
txt1 and txt2 are never likely to be null, unless you've done something horrible wrong...
You should check to see what button was pressed first, that will allow you to make a clearer decision on how to progress.
You should then check the text from the fields and decide on which conversion path you want to go on...
try {
if (e.getSource() == b1) {
String dec = txt1.getText();
String bin = txt2.getText();
if (dec != null && dec.trim().length() > 0 &&
bin != null && bin.trim().length() > 0) {
// Both fields are filled out?!
} else if (dec != null && dec.trim().length() > 0) {
String value = txt1.getText();
int i = Integer.parseInt(dec);
String z = Integer.toBinaryString(i);
txt2.setText(z);
} else if (bin != null && bin.trim().length() > 0) {
int x = Integer.parseInt(bin, 2);
txt1.setText("" + x);
}
} else if (e.getSource() == b2) {
txt1.setText("");
txt2.setText("");
}
} catch (NumberFormatException exp) {
exp.printStackTrace();
}
Related
I am trying to validate my roll no (input of integer value) from JTextField. Well my code is compiling but while running it is giving me an error NumberFormatException.
Here is my validation code
public int rno_vd() {
int a=0,b=0,c=0,x=0,y=0;
int vrno =Integer.parseInt(txtRno.getText());
String r = String.valueOf(vrno);
if (r.isEmpty()) {
JOptionPane.showMessageDialog(null,"rno should not be empty");
a=1;
}
else if (Pattern.matches("[a-zA-Z]+",r)) {
JOptionPane.showMessageDialog(null,"rno should be in digits");
b=1;
}
else if (vrno < 0) {
JOptionPane.showMessageDialog(null,"rno cannot be negative");
c=1;
}
System.out.println(a + b + c);
if (a==1 || b==1 || c==1) {
x=1;
return x;
}
else {
y=0;
return y;
}
}
error
C:\Users\Hp\Desktop\jproject>javac -cp hibernatejar\* *.java
Note: DBHandler.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
C:\Users\Hp\Desktop\jproject>java -cp hibernatejar\*;. Sms
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: ""
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
at java.base/java.lang.Integer.parseInt(Integer.java:662)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at AddFrame.lambda$new$1(AddFrame.java:80)
at java.desktop/javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1967)
at java.desktop/javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2308)
at java.desktop/javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:405)
at java.desktop/javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:262)
at java.desktop/javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:279)
It is getting NumberFormatException, when text field has empty value.
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: ""
Could you please try to validate the text first, and then parse the string?
// Validating text input first
String r = txtRno.getText();
if (r.isEmpty())
{JOptionPane.showMessageDialog(null,"rno should not be empty");
a=1;}
else if (Pattern.matches("[a-zA-Z]+",r))
{JOptionPane.showMessageDialog(null,"rno should be in digits");
b=1;}
else if (vrno < 0)
{JOptionPane.showMessageDialog(null,"rno cannot be negative");
c=1;}
// Converting to int, if validation is successful
int vrno =Integer.parseInt(txtRno.getText());
Komal here as I can see you want to validate JTextField for roll numbers ie should only contain integers, any other character instead of numbers should not be accepted...
Well, I suggest you to try validating on every keyReleased using KeyListener of KeyEvent.
Every key you press is validated if its number its good to go if its not it will show Dialog box saying "only numbers accepted".
I am sharing my code I hope it might help
//********function to check if value is numric or not*********
public static boolean isNumeric(String str) {
try {
Integer.parseInt(str);
return true;
}
catch(NumberFormatException e){
return false;
}
}
//************************function ends******************************
//txtRno is my JTextField
txtRno.addKeyListener(new KeyListener(){
public void keyPressed(KeyEvent e)
{
//code
}
public void keyReleased(KeyEvent e)
{
String value = txtRno.getText();
int l = value.length();
if(!isNumeric(value) && l>0){//if not numric it will not allow you to edit JTextField and show error message
txtRno.setEditable(true);
JOptionPane.showMessageDialog(c,"You need to enter number","ERROR",JOptionPane.ERROR_MESSAGE);
txtRno.requestFocus();
txtRno.setText("");
txtRno.setEditable(true);
lblError.setText("");
}
else { //else it will take the input as it already number or integer
txtRno.setEditable(true);
lblError.setText("");
}
}
public void keyTyped(KeyEvent e)
{
//code
}
});
I'm currently working on a search method in school and I'm stuck in a newbie mistake.
I havent been programming for long and I tried searching the internet for solutions but couldnt find any. I would need to get a number range from 1-10 from the textfield and then put it as an int. Once I've done that I would have to send it to my search method which I am working on. Thanks in advance peeps.
String Value = txfSort.getText();
int NumberValue = Integer.valueOf(Value);
Probably you should first limit the input of textFields to nummeric values. You can help your self with question here: What is the recommended way to make a numeric TextField in JavaFX?
public class NumberTextField extends TextField
{
#Override
public void replaceText(int start, int end, String text)
{
if (validate(text))
{
super.replaceText(start, end, text);
}
}
#Override
public void replaceSelection(String text)
{
if (validate(text))
{
super.replaceSelection(text);
}
}
private boolean validate(String text)
{
return text.matches("[0-9]*");
}
}
Code by: Burkhard
Above code would automaticly check on entry if input is ok. So then you just check, if value is > 0 and < 10. If that is true you just call your method and use value of textField.
One way of doing described would be this:
int value = Integer.valueOf(txfSort.getText());
if(value > 0 && value < 10)
{
myMethod(value);
}
try that one:
textField.addKeyListener(new KeyAdapter(){
public void keyTyped(KeyEvent e) {
char caracter = e.getKeyChar();
if (((caracter < '0') || (caracter > '9')) // for numbers only
&& (caracter != '\b')) {
e.consume();
}
if (Integer.valueOf(textField.getText() + caracter) > 10) {
e.consume(); // if on the text field the numbers are bigger
// than 10, consumes the last number typed
}
}
});
I have started to work on my first Java program, which is a simple calculator, however I get an error claiming that my array is out of bounds. I have tried to debug it to see where and why that is so, as well as following the code on paper, both of which display the results that I would expect and wish for. Therefore, I can not see where the problem actually lies. The code is not complete.
According to the debugger, the error occurs at this line:
answer = outputNum.get(operationIndex) * outputNum.get(operationIndex+1);
Here is the main part of the code that I currently have:
private class ButtonHandler implements ActionListener {
/*
* "outputNum" stores the numbers entered in order.
* "orderOfOperations" stores all numbers in order after multiplication and division has been taken care of.
* "operationList" stores the mathematical operations entered in order.
* "currentNum" stores the most recently inputed numbers.
* "currentString" stores the most recently inputed string of numbers.
* "answer" stores temporary values and ultimately the answer to the inputed equation.
* "start" stores whether or not the equals button has been pressed and a new equation has started.
*/
ArrayList <Double> outputNum = new ArrayList <Double> (0);
ArrayList <Double> orderOfOperations = new ArrayList <Double> (0);
ArrayList <String> operationList = new ArrayList <String> (0);
Double currentNum = 0.0;
String currentString = "0";
Double answer = 0.0;
boolean start = false;
public void actionPerformed(ActionEvent event) {
if(event.getSource() == equalsBtn) {
/* Takes the current numbers string and convert it into a double.
* Let the order of operations be the inputed order for now.
* "operationIndex" to get values inside of the unchanging arrays "outputNum" and "operationList".
* "orderIndex" to get values inside of the changing array "orderOfOperations".
*/
currentNum = Double.parseDouble(currentString);
outputNum.add(currentNum);
orderOfOperations = outputNum;
int operationIndex = 0;
int orderIndex = 0;
//Cycle through the mathematical operations that occur in the current equation.
for(String operation : operationList) {
if(operation == "x" || operation == "รท") {
// Multiply/divide numbers with the multiply/divide operations together.
if(operation == "x") {
answer = outputNum.get(operationIndex) * outputNum.get(operationIndex+1);
}
else {
answer = outputNum.get(operationIndex) / outputNum.get(operationIndex+1);
}
// Replace numbers multiplied/divided in the above statement with the new answer.
orderOfOperations.remove(orderIndex);
orderOfOperations.set(orderIndex, answer);
orderIndex++;
}
operationIndex++;
}
// Reset variables to the default values for the new equation.
System.out.println(orderOfOperations);
outputString = answer.toString();
answer = 0.0;
currentNum = 0.0;
currentString = "0";
outputNum.clear();
operationList.clear();
orderOfOperations.clear();
start = true;
}
else if(event.getSource() == additionBtn || event.getSource() == subtractionBtn || event.getSource() == multiplicationBtn || event.getSource() == divisionBtn) {
// Sets the text fields text blank if this is the start of a new equation.
if(start) {
outputString = "";
start = false;
}
/*
* Takes the current numbers string and convert it into a double.
* Add the mathematical operation and reset the current number.
*/
currentNum = Double.parseDouble(currentString);
outputNum.add(currentNum);
operationList.add(event.getActionCommand());
currentString = "0";
outputString = String.format("%s%s", outputString, event.getActionCommand());
}
else {
// Sets the text fields text blank if this is the start of a new equation.
if(start) {
outputString = "";
start = false;
}
// Adds the button value to the text field text and the current number being inputed.
currentString = String.format("%s%s", currentString, event.getActionCommand());
outputString = String.format("%s%s", outputString, event.getActionCommand());
}
outputScreen.setText(outputString);
}
}
Here is the error message that I get:
Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
at java.util.ArrayList.RangeCheck(ArrayList.java:547)
at java.util.ArrayList.get(ArrayList.java:322)
at MainWindow$ButtonHandler.actionPerformed(MainWindow.java:141)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2028)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2351)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6414)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3275)
at java.awt.Component.processEvent(Component.java:6179)
at java.awt.Container.processEvent(Container.java:2084)
at java.awt.Component.dispatchEventImpl(Component.java:4776)
at java.awt.Container.dispatchEventImpl(Container.java:2142)
at java.awt.Component.dispatchEvent(Component.java:4604)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4618)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4279)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4209)
at java.awt.Container.dispatchEventImpl(Container.java:2128)
at java.awt.Window.dispatchEventImpl(Window.java:2492)
at java.awt.Component.dispatchEvent(Component.java:4604)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:717)
at java.awt.EventQueue.access$400(EventQueue.java:82)
at java.awt.EventQueue$2.run(EventQueue.java:676)
at java.awt.EventQueue$2.run(EventQueue.java:674)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:86)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:690)
at java.awt.EventQueue$3.run(EventQueue.java:688)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:86)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:687)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:296)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:211)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:196)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:188)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
When operationIndex is equal to the last element index in outputNum, then operationIndex + 1 will be greater than the last element index: hence your exception
You would be better off using a for loop that started at index 1, and doing:
// assuming that operationList and outputNum always
// have the same number of elements
for (int i = 1; i < operationList.size(); i++) {
...
answer = outputNum.get(i - 1) * outputNum.get(i);
...
}
or, alternatively, use your current loop, but do:
// operationIndex++; // remove this and use ..
if (++operationIndex >= outputNum.size()) break;
You are only ever adding one item to your list:
currentNum = Double.parseDouble(currentString);
outputNum.add(currentNum);
Then you try to access what seems to be a second object at index operationindex +1 which doesn't exist:
answer = outputNum.get(operationIndex) * outputNum.get(operationIndex+1);
I am creating a budget program in java and need to check to see if the user inputs a valid dollar amount, specifically 2 decimal places. There is no specification on how this should be done.
This is my current attempt but the logic is wrong
aExpense5.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String desc = aExpense3.getText();
String value = aExpense4.getText();
double fValue = 0;
try
{
fValue = Double.valueOf(value);
}
catch (NumberFormatException d)
{
JOptionPane.showMessageDialog(null, "Invalid Number1");
}
double dValue = (fValue * 10) % 10;
if (dValue <= 0)
{
updateExpenseList(desc, fValue);
}
else
{
JOptionPane.showMessageDialog(null,"invalid Number");
}
}
});
You can use regex:
if (value.matches("\\d*\\.\\d\\d")) {
// the number string has two decimal places
}
This regex allows for optional whole number part, ".05" would match.
Try something like:
if (fValue*100 == (int)(fValue*100)) {
//fValue had 2 decimal places or less
}
If fValue = 0.11 then fValue*100 = 11. So you'd have 11 == (int)11 which is true.
If fValue = 0.111 then fValue*100 = 11.1. So you'd have 11.1 == (int)11.1 which is false.
I have two questions regarding character and numeric values limitation. I have listening to focus lost events and validating Name (character) and Contact (numeric) TextFields.
1. How do I restrict numeric data less then 3 digits and not allow more then 13 digits.
Below is the coding of my contact TextField for numeric:
private void txt_contactFocusLost(java.awt.event.FocusEvent evt) {
if (txt_contact.getText().equals("")) {
} else {
String contact = txt_contact.getText();
Pattern pt6 = Pattern
.compile("^[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]+$");
Matcher mh6 = pt6.matcher(contact);
boolean matchFound6 = mh6.matches();
if (!(matchFound6)) {
JOptionPane.showMessageDialog(null,
"* Enter the Numaric Values only *");
txt_contact.setText("");
txt_contact.requestFocus();
}
}
}
2. How do I restrict character data less then 3 character and not allow more then 30 characters.
private void txt_nameFocusLost(java.awt.event.FocusEvent evt) {
if (txt_name.getText().equals("")) {
error2.setText("Enter Full Name");
txt_name.setText("");
} else {
String name = txt_name.getText();
Pattern pt1 = Pattern.compile("^[a-zA-Z]+([\\s][a-zA-Z]+)*$");
Matcher mh1 = pt1.matcher(name);
boolean matchFound1 = mh1.matches();
if (!(matchFound1)) {
JOptionPane.showMessageDialog(null,
"* Enter the Character Values only *");
txt_name.setText("");
txt_name.requestFocus();
} else {
error2.setText("");
}
}
}
You can do something easier:
NumberFormat numF = NumberFormat.getNumberInstance();
numF.setMaximumIntegerDigits(13);
numF.setMinimumIntegerDigits(3);
JFormattedTextField THE_FIELD = new JFormattedTextField(numF);
(The same idea for characters)
Now, only numbers are allowed, with the specified length range.
Read more about it: NumberFormat and JFormattedTextField
in the pattern you can use the statement {n,m} n- to m- times
Duo to this you can build your pattern like this
for your charackter comparison
Pattern pt6=Pattern.compile("[a-zA-Z]{3,30}"); // it says, it should be 3-30 non Digits
for the numbers it is
Pattern pt6=Pattern.compile("\\d{3,13}"); // it says, it should be 3-13 Digits
For String
public boolean validateString(String data){
char [] chars = data.toCharArray();
if(chars.length < 3 || chars.length >13)
return false;
return true;
}
For Number
public boolean validateNumber(int number){
String data = number+"";
return validateString(data);
}
I'm using this one. very simple and easy
use the method that you need or both then call where you need pass your JTextField as parameter done...
public static void setNumericOnly(JTextField jTextField){
jTextField.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();
if ((!Character.isDigit(c) ||
(c == KeyEvent.VK_BACK_SPACE) ||
(c == KeyEvent.VK_DELETE))) {
e.consume();
}
}
});
}
public static void setCharacterOnly(JTextField jTextField){
jTextField.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();
if ((Character.isDigit(c) ||
(c == KeyEvent.VK_BACK_SPACE) ||
(c == KeyEvent.VK_DELETE))) {
e.consume();
}
}
});
}