So I have two boxes where you type in your numbers, and when clicked, it divides number one by number two and sets the label with the answer. (In a perfect world.)
However, you can also write down a word..
I got this for that:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
// the String to int conversion happens here
numberOne = Integer.parseInt(jTextField1.getText().trim());
// print out the value after the conversion
System.out.println("int i = " + jTextField1);
}
catch (NumberFormatException nfe) {
System.out.println(nfe.getMessage() + " is not a number... ");
}
//numberOne = Integer.jTextField1
answer = calc.calculateNumbers(numberOne,numberTwo);
jLabel1.setText(answer);
}
Now instead of getting the error message in the console, I want the label (of the answer) to be set as message.
So, something like: jLabel.setText(ERROR MESSAGE)
but when I put it in the catch, I can't get it to work.
Thanks in advance!
The simple solution is to avoid catching the Exception too early and pretending it didn't happen.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String text = jTextField1.getText().trim();
try {
// the String to int conversion happens here
int numberOne = Integer.parseInt(text);
String answer = calc.calculateNumbers(numberOne, numberTwo);
jLabel1.setText(answer);
} catch (NumberFormatException nfe) {
jLabel1.setText(text + " is not an integer... ");
}
}
Try to place the catch after the code which you can't run if the exception occurs. Also avoid using fields when you could use local variables.
Reading #Peter Lawrey's comment, I realized I did
jLabel1.setText();
twice..
Looking like this:
catch (NumberFormatException nfe) {
System.out.println(nfe.getMessage() + "is not a number... ");
jLabel1.setText(nfe.getMessage());
}
answer = calc.calculateNumbers(numberOne,numberTwo);
jLabel1.setText(answer);
Apparently I COULD set the jLabel's text to something, but I overrode it with the second .setText();..
Thank you guys however!
Related
I'm writing a java program that adds two numbers with any length(the input is string). it works well but the judge gives me 44 because it has "Runtime Error"
what should i do?
To Answer your question "How to handle runtime-errors",
It is not different from any other exception:
try {
someCode();
} catch (RuntimeException ex) {
//handle runtime exception here
}
This judge may have given you a 44 (assuming that is low) because the input that comes to you as strings may not be numbers at all, and if this happens, your program should not crash? That would be my guess
UPDATE: Now that you have some code up, this is most likely the case, what happens if String a is "hello" ? Your program would crash at Long.parseLong(), you need to handle this!
Replace all your calls to Long.parseLong, by calls to such a method :
private long checkLong(String entry){
long result = 0;
try
{
result = Long.parseLong(entry);
}
catch(NumberFormatException e)
{
System.out.println("Value " + entry + " is not valid") ;
System.exit(1);
}
return result;
}
I have a problem that when I use Integer.parseInt in this context it doesn't convert my and somehow it even kick me out of loop so it dont't want to display for example System.out.print(1) after loop like everything was crashed but i have no error. Please help. That's a part of code which cause it. variable "input" is an Arrayl
for (int i=0;i<input.size();i++)
{
if(point>Integer.parseInt(input.get(i).split(":")[1]))
{
input.set(i,highScore + System.getProperty("line.separator"));
break;
}
}
Have you verified that input.get(i).split(":")[1] gives you exactly a string that only contains digits?
Integer.parseInt(String s) throws NumberFormatException, so you should execute that code inside a try/catch block like this:
for (int i=0;i<input.size();i++) {
try {
int parsedValue = Integer.parseInt(input.get(i).split(":")[1]);
// do whatever you want to do with parsedValue
}
catch(NumberFormatException e) {
System.out.print("I caught an error!, what i was trying to parse wasn't a number");
// or any other action you consideer that needs to be done when parseInt fails
}
}
There is only one explanation (if you are sure that no exception is thrown): the input is empty. :)
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 :)
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.
}
}
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.