How to check an empty Double JTextField - java

I've been working this for 2 days but I can't still figure how to check if the jtextfield is empty (Double not String) before passing it to my database.
I figured it out how to validate String if the field is empty, but I need to put the right code on how to validate Double if the field is empty.
Thanks in advance.
Here's my code:
private void saveButton3ActionPerformed(java.awt.event.ActionEvent evt) {
String inventcodef = inventCodeField.getText();
String inventnamef = inventNameField.getText();
String categ = cmbname.getSelectedItem().toString();
double inventreorderf = Double.parseDouble(inventReorderField.getText());
..............
if ((inventCodeField.trim().Length()==0) || (inventNameField.trim().Length()==0)

To enforce formatting (numeric etc) you can use JFormattedTextField.
To ensure values are not blank see No blanks in JTextField

You are reading the double at first as a String. So, you can do something like this:
double inventreorderf;
if (inventReorderField.getText().trim().length == 0)
{
//Do something which should happen when the field is empty
}
else
{
try
{
inventreorderf = Double.parseDouble(inventReorderField.getText());
}
catch (Exception e)
{
//The user has entered an invalid number. Notify him/her here.
}
}

Related

how add the exception handling after accpeting input in JTextField in java

This is the GUI form that I have created. The value is obtained from the text field and it is stored in the new variable. For some value, it needs to be converted into the integer type. I have converted the value to the integer type, but I am trying to handle the exception when the user doesn't enter any value in the text field. for that, I have used if statement. And for the next exception is when the user enters the string value into the integer field. So I am not been able to handle this exception properly. please help me in doing so.
public void addSeniorDev(){
String plat=txt1.getText();
String name = txt2 .gettText();
String hours = txt3.getText();
String period = txt4.getText();
String salary = txt5.getText();
if( plat==("") || name==("") || hours==("")|| period==("")|| salary==
("")){
JOptionPane.showMessageDialog(DA,"The field are left empty:");
}try{
int hours1 = Integer.parseInt(hours);
int salary1 = Integer.parseInt(salary);
int period1 = Integer.parseInt(period);
}catch(ArithmeticException e){
JOptionPane.showMessageDialog(DA,"only number are accepted");
}
}
First of all you cannot compare Strings like that. Use equals method or isEmpty() to check if String is empty. Second thing is that if String is not parsable to Integer it throws NumberFormatException not an ArithmeticException according to documentation:
https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String)
public void addSeniorDev(){
String plat=txt1.getText();
String name = txt2 .gettText();
String hours = txt3.getText();
String period = txt4.getText();
String salary = txt5.getText();
if(plat.isEmpty() || name.isEmpty() || hours.isEmpty() || period.isEmpty()|| salary.isEmpty()) { // changed String comparison
JOptionPane.showMessageDialog(DA,"The field are left empty:");
}try{
int hours1 = Integer.parseInt(hours);
int salary1 = Integer.parseInt(salary);
int period1 = Integer.parseInt(period);
}catch(NumberFormatExceptione){ // Changed exception type
JOptionPane.showMessageDialog(DA,"only number are accepted");
}
}
It is never advisable to do like this
plat==("")
do it like this
StringUtils.isEmpty(plat)
and instead of putting integer parsing under try catch you can avoid it with
StringUtils.isNumeric(hours)
and if this condition comes out to false you can take the required action.
Note : StringUtils is available under import apache.commons.lang3

Having converting and getting data problems [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I wrote a program that calculates Acceleration. This is how it looks:
http://prntscr.com/57yngo
when you press that button it show a dialog message that is a part of JOptionPane. The data you enter in fields are Strings I convert them to double by doing :
double name = Double.valueOf(String);
The problem is if you inserted a String value instead of a double value in the fields you and pressed the button that sends the acceleration total the program badly crash. I really need a solution to fix that!
If you said why did you set the inserted value as String I will answer
that this is the only way to do the
Textfieldname.gettext();
If you knew a way to get a double only from a text field please tell me it.
Try something like this:
public static void main(String[] args) {
String[] values = {"1.0", "2.0", "a"};
for (String value: values) {
System.out.println(getValue(value));
}
}
private static Double getValue(String valueString) {
Double result;
try {
result = Double.valueOf(valueString);
} catch (NumberFormatException e) {
result = 0.0;
}
return result;
}
You have to catch NumberFormatException to handle wrong input
Example:
try {
result = Double.valueOf(valueString);
} catch (NumberFormatException e) {
//show alert and clean field or something else
}
Check IF the String in the textfield can be parsed to Double before the conversion. If you expect simple String values like 3.01 or 150 then a simple regular expression would do:
import java.util.regex.Pattern;
// some stuff in your class
// and in your action listner
Pattern p = Pattern.compile("\\d+|\\d+\\.\\d+"); //digits or digits dot digits
String valueToTest = Textfieldname.gettext();
boolean canBoConverted = p.matcher(valueToTest).matches();
if (canBoConverted) {
double name = Double.valueOf(String);
// do something with name
} else {
// idicate a bad input value to the user
}
If you need a wider range o possible values than you can use the pattern from the Double class documentation
Also please remember that a programmer should always validate user input against whats acceptable.

Catching String exceptions

I'm making a jTextField restrict integer input in netbeans and I don't know what to do.
I'm doing it like this:
private void txtNameKeyReleased(java.awt.event.KeyEvent evt) {
try {
String j = (String) txtName.getText();
} catch ("Which Exception to Catch?") {
if (!txtAge.getText().isEmpty()) {
jOptionPane1.showMessageDialog(null,
"Please enter string values");
txtAge.setText(txtAge.getText().replaceAll("[^a-z]", ""));
}
}
}
What should I put on the catch?
You could just test the input against a regular expression using String.matches() to make sure it's only digits (no need to catch an exception such as a NumberFormatException - it can be considered bad practice to provoke exceptions to validate conditions).
String j = txtAge.getText();
if (!j.matches("\\d+")) {
// It is not a number
}
If you just want to try to convert to an Integer directly and catch an exception you should use Integer.parseInt() (it will throw a NumberFormatException if the input can't be parsed as an Integer):
String j = txtAge.getText();
try {
Integer i = Integer.parseInt(txtAge);
}
catch (NumberFormatException e) {
// j isn't a number...
}
EDIT: There seems to be a little confusion with the answer you provided. In your question the error message was Please enter integer values, as if valid input was only digits. In the answer you posted the message was Please enter String values.
If you want to validate the input doesn't have any numbers, you'll have to use another regex, such as .*\\d.*". If it matches, it means it has a digit. Or you could also use \\D+ to ensure it has one or more non-digits.
I've solved my problem like this:
private void txtNameKeyReleased(java.awt.event.KeyEvent evt) {
String j = (String)txtName.getText();
if ( j.matches("\\d+") && !txtName.getText().isEmpty()) {
jOptionPane1.showMessageDialog(null, "Please enter String values");
txtName.setText("");
} }
Thanks for the ones who tried to help me :)

Display message dialog if JTextField does not contain data

I am writing a BMI calculator application. Currently an error happens which causes the program to stop working if I do not enter data into one field. For instance, there are two JTextFIelds for 'height', one being feet and the other inches. If I just input '6' into the feet JTextField and enter nothing into inches JTextField, then enter my weight in the weight JTextField and click on calculate, it does not work.
What I want to do is display a message dialog saying "Please make sure all fields are filled in" if one field does not contain data.
Below is the ActionHandler code that is added to my 'Calculate' button.
public void actionPerformed(ActionEvent e) {
double heightFT = ((Double.parseDouble(heightFt_TF.getText()));
double heightIn = (Double.parseDouble(heightIn_TF.getText()));
double weight = (Double.parseDouble(weight_TF.getText()));
double totalHeight = (heightFT*12) + heightIn;
BMI = (weight / (totalHeight*totalHeight)) * 703;
String s = BMI+"";
s = s.substring(0,4);
BMI_TF.setText(s);
}
Solved
I have now fixed the problem. What I did was add 'throws NumberFormatException' in the method and did a try catch. In the try code block I wrote the code I want to execute if all data fields are entered. In the catch clause I wrote code that uses the NumberFormatException and simply displays the message dialog with the error message. Now, if one field is not entered, the message dialog appears!
Just check if your JTextField objects contain text.
E.g:
if (heightFt_TF.getText() == null || heightIn_TF.getText() == null || weight_TF.getText() == null) {
JOptionPane.showMessageDialog(null, "Please make sure all fields are filled in");
}
Of course you also have to make sure, that the content of the textfields really contains a number.
Download Apache Commons Lang library and use StringUtils.isBlank(myTextField.getText()); to validate your fields.
public boolean validateFields() {
if (StringUtils.isBlank(heightFt_TF.getText()) {
// show message
return false;
}
if (StringUtils.isBlank(weight_TF.getText()) {
// show message
return false;
}
return true;
}
Only run your calculation if validateFields() returns true.
public boolean validate(JTextField field) {
boolean result = field.getText() != null;
if (result) {
try {
Double.parseDouble(field.getText()));
} catch(NumberFormatException e) {
result = false
}
}
return result;
}

How to validate if Text entered is a numeric number?

I have a calculation application which I need to validate the fields to check if the values entered are numeric numbers and not alphanumeric. I have some ideas about the codes.
Please guide me if I have done anything wrong or seem noob as this is my first time trying out Swing.
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
String text1 = jTextField1.getText(); // TODO add your handling code here:
}
private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {
String text2 = jTextField2.getText(); // TODO add your handling code here:
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if (text1 and text2 != <numeric number>){
JOptionPane.showConfirmDialog(null, "Please enter numbers only", "naughty", JOptionPane.CANCEL_OPTION);
}
// First we define float variables.
float num1, num2, result;
// We have to parse the text to a type float.
num1 = Float.parseFloat(jTextField1.getText());
num2 = Float.parseFloat(jTextField2.getText());
// Now we can perform the addition.
result = num1+num2;
// We will now pass the value of result to jTextField3.
// At the same time, we are going to
// change the value of result from a float to a string.
jTextField3.setText(String.valueOf(result));
// TODO add your handling code here:
}
Please do help. By the way why does my NetBeans keep informing me that it does not recognize the "JOptionPane" Command?
Float.parseFloat() will throw a NumberFormatException if the String isn't numeric and cannot be parsed into a Float. You can add a try-catch block to check for this condition:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
float num1, num2, result;
try {
num1 = Float.parseFloat(jTextField1.getText());
num2 = Float.parseFloat(jTextField2.getText());
result = num1+num2;
jTextField3.setText(String.valueOf(result));
} catch (NumberFormatException e) {
JOptionPane.showConfirmDialog(null, "Please enter numbers only", "naughty", JOptionPane.CANCEL_OPTION);
}
}
If alphanumeric input is not valid for the Swing component in the first place, then instead of validating this post-entry, you should restrict the component to accept only certain format in the first place.
Using the formatters that Swing provides, you can set up formatted text fields to type dates and numbers in localized formats. Another kind of formatter enables you to use a character mask to specify the set of characters that can be typed at each position in the field. For example, you can specify a mask for typing phone numbers in a particular format, such as (XX) X-XX-XX-XX-XX.
That said, you can, among other things, use Integer.parseInt(String s) to see if an arbitrary string can be parsed into an int; the method throws NumberFormatException if it can't. There are also Double.parseDouble, etc.
See also
Java Tutorials/Swing/How to use Formatted Text Field
How to use the Focus Subsystem/Input Validation
Java Tutorials/Internationalization/Formatting - Numbers and Currencies
Related questions
A simple way to create a text field (or such) that only allows the user to enter ints/doubles in Java?
A textbox class only accept integers in Java
Validating an integer or String without try-catch - java.util.Scanner option
try {
Integer.parseInt(foo);
} catch (NumberFormatException e) {
// Naughty
}
Try this:
String temp = txtField.getText();
try
{
int val = Integer.parseInt(temp);
}
catch(NumberFormatException e) {
System.out.println("Invalid");
}
To make it more enjoyable, use JOptionPane (makes it more more interactive)
textFieldCrDays = new JTextField();
textFieldCrDays.addKeyListener(new KeyAdapter() {
//// validate onlu numeric value
public void keyTyped(KeyEvent e) {
if (textFieldCrDays.getText().length() < 3 && e.getKeyChar() >='0' && e.getKeyChar() <= '9')
{
// Optional
super.keyTyped(e);
}
else
{
// Discard the event
e.consume();
}
}
});
A relatively old question, but I figured I would take a shot at it, to maybe help out the random Google Searches.
Another approach someone could take to minimise code and reduce the number of additional classes is to add a KeyListener for the keyType event and check for the Char value. This isn't very portable (you can't use region specific formatting such as numerical punctuation), but this could be quite helpful for straight integers.
You could also do a relative length here as well:
textField.addKeyListener(new KeyAdapter()
{
#Override
public void keyTyped(KeyEvent keyEvent)
{
if (textField.getText().length() < 3 && keyEvent.getKeyChar() >= '0' && keyEvent.getKeyChar() <= '9')
{
// Optional
super.keyTyped(keyEvent);
}
else
{
// Discard the event
keyEvent.consume();
}
}
});
You can also add another event listener to validate the entire integer for further processing (the entire number must be > 800 and < 5220 for example).
A good place for this would be on the focusLost event(?).
If you are doing these features frequently, it would be best to subclass the JTextField class to provide this functionality.
EDIT: Using Character.isLetter(keyEvent.getKeyChar()) is even more clear.

Categories

Resources