JTextfield Validation for numbers? - java

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
}
});

Related

Validating user input in arrays

Hey guys I am doing a project for school and am having a little trouble, I have a variable "reservationNumber" and im attempting to check if the number the user inputs is in the array, if not it returns a string saying the number was not found. It is working fine and displays the correct info when there is a valid input but when an invalid input is detected it gives a null.pointer.exception error. I tried writing it so that if the number is not detected the private method returns -1, then when I call the tickerInformation method, if that the variable 'ticket' returns -1 then it returns "invalid reservation number". This is where is error is being raised and only occurs when I enter an invalid number please help.
public void ticketInformation(String reservationNumber)
{
int ticket = searchArray(reservationNumber);
if (ticket == -1)
{
System.out.println("The reservation number entered was n0t found");
}
else
{
System.out.print("\n" + ticketSale[ticket].toString());
}
}
private int searchArray(String reservationNumber)
{
for (int i = 0; i < ticketSale.length; i++)
{
if (ticketSale[i].getReservationNumber().equals(reservationNumber))
{
return i;
}
}
return -1;
}
ticketSale[i].getReservationNumber().equals(reservationNumber) has an issue. Share the declaration and init for array "ticketSale". If ticketSale array is for abstract data type then why equal is called with String?
You didn't post the whole code but I think that when you enter invalid number as reservation number, it does not assigned to the related object's instance variable. So getReservationNumber() might be returning null.
Add a null check,
private int searchTicketSales(String reservationNumber) {
int reservationNumberIndex = -1;
for (int i = 0; i < ticketSale.length; i++) {
if (null != ticketSale[i].getReservationNumber() && ticketSale[i].getReservationNumber().equals(reservationNumber)) {
reservationNumberIndex = i;
break;
}
}
return reservationNumberIndex;
}
Best Regards,
Rakesh
Add a regex to validate that your input is a valid number "\\d+":
public void ticketInformation(String reservationNumber)
{
String regex = "\\d+";
if(!reservationNumber.matches(regex))
{
System.out.println("The reservation number entered was n0t found");
}
int ticket = searchArray(reservationNumber);
if(ticket == -1)
{
System.out.println("The reservation number entered was n0t found");
}
else
{
System.out.print("\n" + ticketSale[ticket].toString());
}
}
You might want to validate searchArray, particularly if it is not used interdependently from ticketInformation().

How would I get a specific number range from a textfield?

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
}
}
});

Editable to string Crash

I made this code and the program crashes when I try to convert the editable's value to an integer since the texted it type is decimal, and I suspect it's at the point when the application must change the editable to string, due to the fact when the edit text is empty after editing the text it crashes.
EditText Y = (EditText) findViewById(R.id.y);
Y.addTextChangedListener(new TextWatcher(){
#Override
public void afterTextChanged(Editable s) {
if(s != null){
int Yvalue = Integer.parseInt(s.toString());
}
}
It looks more likely to me that the NumberFormatException should be occurring while parsing the String to an Integer. Try enclosing it within the try/catch for that exception.
try {
Yvalue = Integer.parseInt(number);
} catch (NumberFormatException e) {
Yvalue = defaultVal; // or do whatever necessary
}
try to parse the value of string to float and get it in float variable
float Yvalue = Float.parseFloat(s.toString());
Assuming you want integers only, try something like this:
#Override
public void afterTextChanged(Editable s) {
if (s.length() == 0) {
// complain about no input
} else {
try {
int yValue = Integer.parseInt(s.toString());
// ...
} catch (NumberFormatException e) {
// complain about invalid input
}
}
}
I'm not an Android developer, but I'd be surprised if there wasn't a way to add a mask to your input field that prevents anything other than integers being input.

Getting A NumberFormat Exception in BlackBerry

I am trying to parse a string to int value. But i am getting a NumberFormat Exception. I am writing the below code:
Logger.out("Myprof", "Contact "+strContact);
try{
i = Integer.parseInt(strContact.trim());
Logger.out("Myprof", "Contact8686866 "+i);
}
catch(Exception e)
{
Logger.out("Myprof", "exce "+e.toString());
}
Now when i am passing like below:
i = Integer.parseInt("11223344");
I am getting the i value as 11223344.
Where i am doing wrong here? Please Help.
The input value of 9875566521 is greater than Integer.MAX_VALUE of 2147483647. Instead use a Long. (BigInteger not an option for Blackberry)
Long number = Long.parseLong(strContact);
Logger.out("Myprof", "Contact8686866 " + number);
If the intended input numbers are greater then Long.MAX_VALUE, then Character.iDigit can be used as an alternative to validate values:
private static boolean isValidNumber(String strContact) {
for (int i = 0; i < strContact.length(); i++) {
if (!Character.isDigit(strContact.charAt(i))) {
return false;
}
}
return true;
}

Exception error in Java

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();
}

Categories

Resources