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 :)
Related
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!
String texts;
texts = textFieldb.getText();
String textd;
textd = textFieldc.getText();
How would I get it to run a specific function using " if ", example : If 'texts' is a number then it'll run a specific function, and if it wasn't a number, it would run another. Also, how would I do that if it's a word, rather then a number? Thanks. :)
I think it's really simple. You just need to parse your String and catch the exception. If it's in the exception, that's not a number, then you can do any business you want. For example:
String texts = "test";
try {
int intValue = Integer.valueOf(texts);
System.out.println("is number");
} catch(NumberFormatException ex) {
System.out.println("is not a number");
}
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. :)
So when I am doing something like this. I am trying to figure out how to stop the user from simply entering a char or string and producing a runtime error. I am not sure how to filter the input here:
System.out.println("Please enter the degree of difficulty"
+ " for this dive");
while(degreeOfDifficulty > 3.8 || degreeOfDifficulty < 1.2)
{
degreeOfDifficulty = scanner.nextDouble();
}
If you enter a char or string here obviously it will produce an error. Please help! Thanks.
Use scanner.hasNextDouble() instead of try...catch.
It gives whether the next token in the input is a valid double. You can then either get it with scanner.nextDouble() or ignore the token with scanner.next().
You can have a condition to your while loop.
boolean invalidInput = false;
while(!invalidInput && (degreeOfDifficulty > 3.8 || degreeOfDifficulty < 1.2))
{
try {
degreeOfDifficulty = scanner.nextDouble();
invalidInput = false;
} catch (Exception e) {
System.out.println("Your entry was invalid, please enter a double.");
invalidInput = true;
}
}
the most simple will be to use try and catch
This one helped me.!!
Create a boolean mothod as follows.
private boolean preventNonestring(String str) {
Pattern p = Pattern.compile("[^a-z A-Z]");
return p.matcher(str).find();
}
Then use the method as follows
if(preventNonestring(yourtext)){
//Do something here when true
}else{
//Your error message here when false
}
You can use Patterns
Pattern p = Pattern.compile("[^a-z A-Z]");
and then check if the endered character has characters
p.matcher(str).find();
Also use try and catch to avoid run-time errors
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.