How to verify textField input? - java

I know this shouldn't be too difficult but my searching hasn't led to anything useful yet. All I want to do is make sure the user inputs a positive integer into a textField. I've tried:
public class myInputVerifier extends InputVerifier {
#Override
public boolean verify(JComponent jc) {
String text = ((jTextFieldMTU) jc).getText();
//Validate input here, like check int by try to parse it using Integer.parseInt(text), and return true or false
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
So in my main code I want to use this to display "OK" if successful and "Enter a positive number" if not successful.
Can someone point me in the right direction please? Thanks!

You could use a try-catch block to check if the input is an integer:
try {
int i = Integer.parseInt(input);
// input is a valid integer
}
catch (NumberFormatException e) {
// input is not a valid integer
}

String has a matches method you can use with regular expressions to see if the contents match a particular pattern. The regular expression for positive integers is ^[1-9]\d*$ so you can use it like this...
boolean matches = text.matches("^[1-9]\d*$");
if(matches){
//Do something if it is valid
}else{
//Do something if it is not
}

I suggest you use try catch.
Catch the NumberFormatException.
In this way you check if the text can be parsed to an integer. If not you can display an error message to the user.
After that you can us an if else statement to check if the number is positive if not positive you can give the user an error message. I suggest you research try catch if you don't know it.

Related

Parsing large int in Java

I have a JTextField object that a user can type in a number(or anything) into. I am trying to parse this textfield for a number and I do a validation check to see if the number is within a certain range (1-999).
String lowerLimit = this.lowerLimitTextField.getText().trim();
String upperLimit = this.upperLimitTextField.getText().trim();
if( Integer.parseInt(lowerLimit) < 1 || Integer.parseInt(upperLimit) > 999 )
{
return "The string must be in the range 0-999";
}
My issue is that, the user can specify any value into the textfield. When I try to input something like "61412356123125124", I get a NumberFormatException when parsing the string. What would be the simplest way to handle such a case? I do have a check that makes sure that the inputted string is all numbers, so thats fine.
I have tried changing the parseInt() into a parseLong() but I still get the same issue, since the number inputted is essentially unbounded. Can this be done with parsing the string (preferred), or is the simplest way to set some constraints on the JTextField itself?
Use NumberFormatto parse
import java.text.NumberFormat;
import java.text.ParseException;
public class MyVisitor {
public static void main(String[] args) throws ParseException {
System.out.println(NumberFormat.getNumberInstance().parse("61412356123125124"));
}
}
outputs
61412356123125124
Looks like you do not want to get the number, just check range (0-999). In this case just catch NumberFormatException and return same string:
try {
if( Integer.parseInt(lowerLimit) < 1 || Integer.parseInt(upperLimit) > 999 ) {
return "The string must be in the range 0-999";
}
} catch (NumberFormatException e) {
return "The string must be in the range 0-999";
//or more relevant message, like "Number to long" or something
}
The answer is that the Exception is your friend: It's telling you the number is too large... Put the error handling in the catch block or better yet declare throws NumberFormatException and catching calling block so that the method can be recalled
So you can use Integer.parseInt, Long.parseLong, or new BigInteger(String)... I would recommend Integer.parseInt in this case. Once you've got an int, you can do bounds checking. And if it's out of bounds, you might just want to throw an NumberFormatException :)

java.lang.NumberFormatException: For input string: "" when using "2" or "5"

I read in a menu choice and typing in any number but 2 & 5 work.
String choice = promptUser(choicePrompt);
try {
outputInfo(String.format("choice=...%s...",choice));
int c = Integer.parseInt(choice);
/* process it */
}catch (NumberFormatException e) {
outputInfo(String.format("choice=%s",choice));
outputInfo(e.toString());
}
public static void outputInfo(String msg)
{
System.out.printf("\t%s\n",msg);
}
Good output:
Enter Option: 1
choice=...1...
Bad Output:
Enter Option: 2
choice=...2...
choice=2
java.lang.NumberFormatException: For input string: ""
Update:
I've hard-coded "2" and it still fails!:
String choice = promptUser(choicePrompt);
try {
choice="2";
outputInfo(String.format("choice=...%s...",choice));
int c = Integer.parseInt(choice);
/* process it */
}catch (NumberFormatException e) {
outputInfo(String.format("choice=%s",choice));
outputInfo(e.toString());
}
Hard-coding "5" also fails but "1" works!!!
Any ideas gratefully received.
Simon
If I assume your promptUser() method to be something like:
static String promptUser() {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
try {
return reader.readLine();
}
catch(Exception ex) {
return null;
}
}
(without the parameter) then the program behaves as expected - certainly there's nothing in that code that treats 2 or 5 differently. If you're getting an empty string then are you sure your prompt user method is working correctly?
Either way, the code you've posted here is essentially correct. I would imagine there's something else wrong in your more fully complete program that doesn't manifest itself when you've reduced it down here; perhaps you're running into a case where a local variable is hiding a field for example and you're not using the value you think you are (but at this point, I'm just guessing.)
updated
Seems the promptUser method is returning an empty String "". check if choice is empty before calling
ParseInt method
Also you can add trim() to eliminate spaces before and after the input
if(choice!=null && !"".equals(choice))
int c = Integer.parseInt(choice.trim());
printStackTrace() is your friend.
Turns out the number format exception was further down (in the 'process it' code) and was not being caught down there.
It was data driven so didn't happen on other machines.
Thanks to every one for your support.
Simon

Input Validation of a Floating Point Number (Inside a Try-Catch Block)

I've tried scouring Google and several sites such as this to find an answer to my question and I'm just not having any luck. I'm in a second-tier Java course in college, and I'm trying to figure out how to do input validation on a floating point number while using a try-catch block. The gist of the scenario is as such:
A driver will call the method promptForMotherHeight(), this method is supposed to pull in a user's entry as a floating point number. The issue is that with the try-catch block, if the Scanner detects a non-floating point number, it won't dump the data out of the scanner's buffer. This leads to an infinite loop. I've tinkered with adding a Scanner.next() inside my catch block, but any data entered after the first attempt will not validate properly (meaning that I can enter in something such as 5.55555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555 and it will accept this as a valid input).
Here's what I'm working with, code-wise (I've imported all the things I need to at the top of the class and motherHeight is a private float instance variable at the top of the class):
public void promptForMotherHeight()
{
String motherHeightPrompt = "Enter mother's height in inches: ";
String motherError1 = "Invalid entry. Must be positive.";
String motherError2 = "Invalid entry. Must be a decimal number.";
boolean valid = false;
do
{
System.out.print(motherHeightPrompt);
try
{
motherHeight = stdIn.nextFloat();
valid = true;
}
catch (InputMismatchException e)
{
System.out.println(motherError2);
stdIn.next();
}
} while(!valid);
}
Any pointers or hints as to how I can accomplish proper input validation would be much appreciated. Thanks
You could do the floating point number validation in the try-catch like this.
do {
System.out.print(motherHeightPrompt);
try {
motherHeight = Float.parseFloat(stdIn.nextLine()); // This will read the line and try to parse it to a floating value
valid = true;
} catch (NumberFormatException e) { // if it was not a valid float, you'll get this exception
System.out.println(motherError2);
// You need not have that extra stdIn.next()
// it loops again, prompting the user for another input
}
} while (!valid); // The loop ends when a valid float is got from the user

JTextfield Listener for Integers

I am having troubles in finding a solution to write a listener for a JTextField specifically to only allow integer values (No Strings allowed). I've tried this recommended link on Document Listener, but I don't know what method to invoke etc.
I've never used this type of Listener before, so could anyone explain how I could write a listener on a JTextField to only allow integer values that can be accepted?
Basically after I click a JButton, and before the data is extracted out onto a variable, then Listener will not allow it to be processed until an integer is inputted.
Thanks very much appreciated.
You don't want a listener, you want to get the text from the JTextField and test if it is an int.
if (!input.getText().trim().equals(""))
{
try
{
Integer.parseInt(myString);
System.out.println("An integer"):
}
catch (NumberFormatException)
{
// Not an integer, print to console:
System.out.println("This is not an integer, please only input an integer.");
// If you want a pop-up instead:
JOptionPane.showMessageDialog(frame, "Invalid input. Enter an integer.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
You could also use a regex (a little bit of overkill, but it works):
boolean isInteger = Pattern.matches("^\d*$", myString);
You don't want a document listener. You want an ActionListener on the submit/ok button.
Make sure that listener is created with a handle to the JTextField, then put this code in the actionPerformed call:
int numberInField;
try {
numberInField = Integer.parseInt(myTextField.getText());
} catch (NumberFormatException ex) {
//maybe display an error message;
JOptionPane.showMessageDialog(null, "Bad Input", "Field 'whatever' requires an integer value", JOptionPane.ERROR_MESSAGE);
return;
}
// you have a proper integer, insert code for what you want to do with it here
how I could write a listener on a JTextField to only allow integer values that can be accepted?
You should be using a JFormattedTextField or a Document Filter.
JFormattedTextField example:
public static void main(String[] args) {
NumberFormat format = NumberFormat.getInstance();
format.setGroupingUsed(false);
NumberFormatter formatter = new NumberFormatter(format);
formatter.setValueClass(Integer.class);
formatter.setMinimum(0);
formatter.setMaximum(Integer.MAX_VALUE);
JFormattedTextField field = new JFormattedTextField(formatter);
JOptionPane.showMessageDialog(null, field);
}
JFormattedTextField works well for restricting input. In addition to limiting input to numbers, it is capable of more advanced use, e.g. phone number format. This provides immediate validation without having to wait for form submission or similar event.

Comparison problems [.equals()] in java

I am trying to determine whether a string contains a positive int or not. My code is:
public void isInt(String str) throws NotIntException{
String integer=str.replaceAll("\\d","");
System.out.println(integer);
if (!integer.equals("")){
throw new NotIntException("Wrong data type-check fields where an integer"+
" should be.");
}//end if
if (integer.equals("-")){
System.out.println(integer);
throw new NotIntException("Error-Can't have a negative count.");
}//end if
}//end method
I am testing this with a string "-1", which should, after the replaceAll(), become "-". This should enter both if-statements. But it only enters the first. I tried it with the == comparison too, just in case, but it didn't work either. What's odd to me is that whether I look to fulfill the second if-statement's condition or to fulfill its negation [i.e., !integer.equals("-")], the program still doesn't enter the if....
Thanks, usually my comparison issues are just me missing something basic, but I really don't see anything here...
Since you are throwing an Exception in your first if, so, your 2nd if will not even be tested.
if (!integer.equals("")){
throw new NotIntException("Wrong data type-check fields where an integer"+
" should be.");
}
if (integer.equals("-")){
System.out.println(integer);
throw new NotIntException("Error-Can't have a negative count.");
}
If your code enters the first if, it will not execute further.
But, why are you using this approach for your problem.
You can easily use Integer.parseInt to check for valid integer. And then if it is valid, then test whether its less than 0. It would be far easier and readable.
My solution:
public static boolean isPositiveInt(String str) {
try {
int number = Integer.parseInt(str.trim());
return number >= 0;
} catch (NumberFormatException e) {
return false;
}
}
If you want to simply read an int from a String, use Integer.parseInt(), although that would only work if you want to see if a string "is" an int, not contains one.
You could use a combination of Integer.parseInt() and a loop strategy to see if it contains an int fairly easily though, then just check if that is positive or not.
You approach is too complicated. I would keep it simple:
if (integer.startsWith("-")) {
// it's a negative number
}
if (!integer.matches("^\\d+$")) {
// it's not all-numbers
}
and forget the call to replaceAll()

Categories