How to check if a string is a valid integer? [duplicate] - java

This question already has answers here:
What's the best way to check if a String represents an integer in Java?
(40 answers)
Closed 8 years ago.
I have:
op1 = Integer.parseInt(jTextField1.getText());
op2 = Integer.parseInt(jTextField2.getText());
However, I want to check first whether the text fields' values can be assigned to integer variables. How do I do that?
I've been going through this for a long time, so, if this was already asked here, forgive me

You can't do if (int i = 0), because assignment returns the assigned value (in this case 0) and if expects an expression that evaluates either to true, or false.
On the other hand, if your goal is to check, whether jTextField.getText() returns a numeric value, that can be parsed to int, you can attempt to do the parsing and if the value is not suitable, NumberFormatException will be raised, to let you know.
try {
op1 = Integer.parseInt(jTextField1.getText());
} catch (NumberFormatException e) {
System.out.println("Wrong number");
op1 = 0;
}

This works for me. Simply to identify whether a String is a primitive or a number.
private boolean isPrimitive(String value){
boolean status=true;
if(value.length()<1)
return false;
for(int i = 0;i<value.length();i++){
char c=value.charAt(i);
if(Character.isDigit(c) || c=='.'){
}else{
status=false;
break;
}
}
return status;
}

parseInt throws NumberFormatException if it cannot convert the String to an int. So you should surround the parseInt calls with a try catch block and catch that exception.

Basically, you have to decide to check if a given string is a valid integer or you simply assume a given string is a valid integer and an exception can occur at parsing.

Related

Input validation in setter method [duplicate]

This question already has answers here:
How to check if a String is numeric in Java
(41 answers)
Closed 3 years ago.
How can I make my setter method public void setYear(String year) check if the input is a number or not? It's for a class exercise. I'm just trying to understand why/how to do this. I don't know why, but it has to be string year, and I need to make sure that only a number can be used.
For example I have:
public void setColour(String colour) {
colour = colour;
}
public void setYear(String year) {
if (Integer.parseInt(year) >= 0) {
//Do stuff here
}
}
Use Integer.parseInt(String s) to check if String year can be convert to an Integer greater or equal to zero (logically, a year can not be negative). If the input can not be converted to an Integer, it will throw a NumberFormatException.
I can propose 2 ways of doing this.
Suppose the string you need to validate is strYear and you consider valid all integer values >= 0.
The 1st is by forcing the string to be casted to an integer and catching any error thrown:
int year = -1;
try {
year = Integer.parseInt(strYear);
} catch (NumberFormatException e) {
e.printStackTrace();
}
boolean validYear = (year >= 0);
The 2nd is eliminating all non numeric chars in the string and compare the result to the original string. If they are the same then the string consists only of digits:
strYear = strYear.trim();
String strOnlyDigits = strYear.replaceAll("\\D", "");
boolean validYear = (!strYear.isEmpty() && strYear.equals(strOnlyDigits));
public int year;
public void setYear(String year){
try {
year = Integer.parseInt(year);
} catch(Exception e) {
e.printStackTrace();
}
}
You can use try and catch to check if the input is a number. In here, you are trying to parse the String into integer. If it only contains a number, it will be able to convert it successfully. On the other hand, if it has some other characters, it will stop and you will get an exception. Try and catch prevents your program from crashing.
At the same time, you can try regular expression to check if it only contains number.
String regex = "[0-9]+";
year.matches(regex );

How to check the type of a value in Java? [duplicate]

This question already has answers here:
Validating input using java.util.Scanner [duplicate]
(6 answers)
Closed 9 years ago.
I'm making a program where I want the user to input a value into a variable. After it is inputted I want to check the value type, but I don't know how. It looks a bit like this:
import java.util.Scanner;
Scanner scanner = new Scanner(System.in);
int num1;
num1 = scanner.nextInt();
I want some way of checking the type of num1, so that I can make sure the user has inputted a usable value i.e. to make sure they haven't inputted a string such as "qwerty" into the integer variable, so that I can go on to catch the error if they have, rather than end up with a java.util.InputMismatchException. I've tried:
if(num1 instanceof java.lang.String)
but it doesn't fix the error and it doesn't work for integers either.
Any ideas on how to fix this?
public boolean isInteger( String input ) {
try {
Integer.parseInt( input );
return true;
}
catch( Exception e ) {
return false;
}
}
Do as the others mentioned and use scanner.next() to retrieve a string. Afterwards you can use the above code snippet to check if a string is an Integer.
For a double it looks pretty similiar:
boolean isDouble(String str) {
try {
Double.parseDouble(str);
return true;
} catch (NumberFormatException e) {
return false;
}
}
Java is a static typed language so scanner.nextInt(); will always return int.
If you want the return type to be String call scanner.next()

function to identify whether the value can be converted to int, or double, or anything else?

If there is a string variable containing a number string , is there any function to identify whether the value can be converted to int, or double, or anything else?? i need the function name in java
String sent3 = "123";
System.out.println(sent3.matches("[0-9]+"));
System.out.println(sent3.matches("[0-9]+\\.[0-9]+"));// for double
output :- true
If the output is true then it can be converted into int.
Follow this link for more regex
My solution involves trying to parse the string into the various types, and then looking for exceptions that Java might throw. This is probably an inefficient solution, but the code is relatively short.
public static Object convert(String tmp)
{
Object i;
try {
i = Integer.parseInt(tmp);
} catch (Exception e) {
try {
i = Double.parseDouble(tmp);
} catch (Exception p) {
return tmp; // a number format exception was thrown when trying to parse as an integer and as a double, so it can only be a string
}
return i; // a number format exception was thrown when trying to parse an integer, but none was thrown when trying to parse as a double, so it is a double
}
return i; // no numberformatexception was thrown so it is an integer
}
You can then use this function with the following lines of code:
String tmp = "3"; // or "India" or "3.14"
Object tmp2 = convert(tmp);
System.out.println(tmp2.getClass().getName());
You can convert the function into inline code to test if it is an integer, for example:
String tmp = "3";
Object i = tmp;
try {
i = Integer.parseInt(tmp);
} catch (Exception e) {
// do nothing
}
I was a little sloppy and tried to catch normal Exceptions, which is rather generic - I suggest you use "NumberFormatException" instead.
String test = "1234";
System.out.println(test.matches("-?\\d+"));
test = "-0.98";
System.out.println(test.matches("-?\\d+\\.\\d+"));
The first one matches (ie prints true) any integer (not int, integer) with an optional - sign in front. The second one matches any double value with an optional - sign, at least one digit before a required decimal point, and at least on digit following the decimal point.
Also, the function name is String.matches and it uses regular expressions.

Get text from textfield

I'm making a GUI program. In my first program I have the following code:
double num1;
num1 = Double.parseDouble(guess.getText());
I believe that this code gets the value from the text field and converts it to double.
How can I get the value and convert it to String or Char?
Since the getText() already returns a String, storing its value as a String is trivial.
In order to parse a double, you've already done it, just watch for the NumberFormatException, in case of invalid input.
To store its value as a char, that depends on your requirements. Do you want the first character? Do you require the string to have only a single character? Is any character valid? And so on.
// Storing the value as a String.
String value = guess.getText();
// Storing the value as a double.
double doubleValue;
try {
doubleValue = Double.parseDouble(value);
} catch (NumberFormatException e) {
// Invalid double String.
}
// Storing the value as a char.
char firstChar = value.length() > 0 ? value.charAt(0) : (char) 0;
// Require the String to have exactly one character.
if (value.length() != 1) {
// Error state.
}
char charValue = value.charAt(0);
use String.valueOf() instead of Double.parseDouble() this will help you convert double into string value
The getText() already returns the text as String.
Btw, be careful of Exceptions due to parse error. But your on the right track. :)
The getText()method returns a String. when you use .parseDouble what you are really doing is turning the string the user entered and into a double therefore in the case of a string you do not have to use a .parse method because the value called is already a string. In the case of a character you would have to use something like this:
String text = jTextField1.getText();
if (text.length() > 1 && !text.contains(" ") && !text.contains(",")) {
//make sure that its length is not over 1, and that it has no spaces and no commas
char ch = text;
} else {
//if a space or comma was found no matter how big the text it will execute the else..
System.out.println("this is not allowed");
jTextField1.setText("");
}
The getText() function already fetches a String value from the Textfield.
For example:
String var = guess.getText();
Here, var is storing the String value received from the Textfield.

Determine if a String is an Integer in Java [duplicate]

This question already has answers here:
What's the best way to check if a String represents an integer in Java?
(40 answers)
Closed 9 years ago.
I'm trying to determine if a particular item in an Array of strings is an integer or not.
I am .split(" ")'ing an infix expression in String form, and then trying to split the resultant array into two arrays; one for integers, one for operators, whilst discarding parentheses, and other miscellaneous items. What would be the best way to accomplish this?
I thought I might be able to find a Integer.isInteger(String arg) method or something, but no such luck.
The most naive way would be to iterate over the String and make sure all the elements are valid digits for the given radix. This is about as efficient as it could possibly get, since you must look at each element at least once. I suppose we could micro-optimize it based on the radix, but for all intents and purposes this is as good as you can expect to get.
public static boolean isInteger(String s) {
return isInteger(s,10);
}
public static boolean isInteger(String s, int radix) {
if(s.isEmpty()) return false;
for(int i = 0; i < s.length(); i++) {
if(i == 0 && s.charAt(i) == '-') {
if(s.length() == 1) return false;
else continue;
}
if(Character.digit(s.charAt(i),radix) < 0) return false;
}
return true;
}
Alternatively, you can rely on the Java library to have this. It's not exception based, and will catch just about every error condition you can think of. It will be a little more expensive (you have to create a Scanner object, which in a critically-tight loop you don't want to do. But it generally shouldn't be too much more expensive, so for day-to-day operations it should be pretty reliable.
public static boolean isInteger(String s, int radix) {
Scanner sc = new Scanner(s.trim());
if(!sc.hasNextInt(radix)) return false;
// we know it starts with a valid int, now make sure
// there's nothing left!
sc.nextInt(radix);
return !sc.hasNext();
}
If best practices don't matter to you, or you want to troll the guy who does your code reviews, try this on for size:
public static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false;
} catch(NullPointerException e) {
return false;
}
// only got here if we didn't return false
return true;
}
It's better to use regular expression like this:
str.matches("-?\\d+");
-? --> negative sign, could have none or one
\\d+ --> one or more digits
It is not good to use NumberFormatException here if you can use if-statement instead.
If you don't want leading zero's, you can just use the regular expression as follow:
str.matches("-?(0|[1-9]\\d*)");
Or you can enlist a little help from our good friends at Apache Commons : StringUtils.isNumeric(String str)
You want to use the Integer.parseInt(String) method.
try{
int num = Integer.parseInt(str);
// is an integer!
} catch (NumberFormatException e) {
// not an integer!
}
Or simply
mystring.matches("\\d+")
though it would return true for numbers larger than an int
As an alternative approach to trying to parse the string and catching NumberFormatException, you could use a regex; e.g.
if (Pattern.compile("-?[0-9]+").matches(str)) {
// its an integer
}
This is likely to be faster, especially if you precompile and reuse the regex.
However, the problem with this approach is that Integer.parseInt(str) will also fail if str represents a number that is outside range of legal int values. While it is possible to craft a regex that only matches integers in the range Integer.MIN_INT to Integer.MAX_INT, it is not a pretty sight. (And I am not going to try it ...)
On the other hand ... it may be acceptable to treat "not an integer" and "integer too large" separately for validation purposes.
You can use Integer.parseInt(str) and catch the NumberFormatException if the string is not a valid integer, in the following fashion (as pointed out by all answers):
static boolean isInt(String s)
{
try
{ int i = Integer.parseInt(s); return true; }
catch(NumberFormatException er)
{ return false; }
}
However, note here that if the evaluated integer overflows, the same exception will be thrown. Your purpose was to find out whether or not, it was a valid integer. So its safer to make your own method to check for validity:
static boolean isInt(String s) // assuming integer is in decimal number system
{
for(int a=0;a<s.length();a++)
{
if(a==0 && s.charAt(a) == '-') continue;
if( !Character.isDigit(s.charAt(a)) ) return false;
}
return true;
}
You can use Integer.parseInt() or Integer.valueOf() to get the integer from the string, and catch the exception if it is not a parsable int. You want to be sure to catch the NumberFormatException it can throw.
It may be helpful to note that valueOf() will return an Integer object, not the primitive int.
public boolean isInt(String str){
return (str.lastIndexOf("-") == 0 && !str.equals("-0")) ? str.substring(1).matches(
"\\d+") : str.matches("\\d+");
}

Categories

Resources