Determine if a String is an Integer in Java [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 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+");
}

Related

How to detect if the user inputs a fraction

I want to only accept fractions.
Here's what I've done so far:
if (nm == 2) {
System.out.print("First Fraction: ");
aa = sc.nextLine();
System.out.print("Second Fraction: ");
bb = sc.nextLine();
if (aa.startsWith("[0-9].*") && aa.contains("/") && aa.endsWith("[0-9].*") && bb.startsWith("[0-9].*") && bb.contains("/") && bb.endsWith("[0-9].*")) {
ar = new Arithmetic_Operations(aa, bb);
} else {
System.out.println("Please Input Fraction");
System.out.println();
break;
}
}
Arithmetic_Operations.Add();
How do I detect that the String starts and ends with a number?
Also, I have no idea what I was doing with the .start and .end codes.
The question can be expressed more generally as "how to write a parser". Generally speaking, regex is not the most straightforward way to tackle it. See here for a more thorough explanation, which can be summarized in your case as follows:
Write a method to check that the input has exactly:
a numerator
a denominator
a division sign between them
This is a pretty simple case, so it'd be overkill to write something really complicated for it but one approach without using regex and with three separate simple "functions" (steps) would be the following:
boolean isFraction(String text) {
String[] numeratorAndDenominator = text.split("/");
// check for the division sign
if (numeratorAndDenominator.length != 2) {
return false;
}
// check that the numerator is an integer
try {
Integer.parseInt(numeratorAndDenominator[0].trim());
} catch (NumberFormatException e) {
return false;
}
// check that the denominator is also an integer
try {
Integer.parseInt(numeratorAndDenominator[1].trim());
} catch (NumberFormatException e) {
return false;
}
return true;
}
For more complicated stuff it would probably be more worth your time to look at existing parsing libraries for mathematical expressions. One possibility might be mathparser.
If you want to detect simple fractions, you can use below method.
public static boolean isFraction(String text){
return (text.matches("[0-9]+[/][0-9]+"));
}
If you want a more complex solution, you need to also check,
+, - signs
Parentheses
More than one /
Fractions
If you are implementing these via regex, below link will help you.
Java regex

How do I check to see if a string has any numbers? [duplicate]

This question already has answers here:
Check and extract a number from a String in Java
(16 answers)
Closed 2 years ago.
So I am supposed to create a method which checks to see if a string contains any numbers. It will return "yes" if it does and "no" if it does not. I think I have done everything correct so far, but am not sure how to use the indexOf() to search for any number ranging from 0 - 9. Please note I am a beginner in javascript, so I would appreciate beginner friendly responses.
String go( String a )
{
int x = a.indexOf( ??? );
{
if (x == -1)
{
return "no";
}
else
{
return "yes";
}
}
}
You can match your string s1 with this regex which checks if there is one or more digits in the string.
boolean hasDigit = s1.matches(".*\\d+.*");
While C++ has a function that's quite suitable for searching for any of several specified chars, in java one must check for each char.
Java equivalent for C++'s "std::string::find_first_of"
If you wish to instead use indexOf, note that it returns -1 if char is not present. You are on the right track, but need to search for each of them.
java:
public boolean hasNum(String s) {
for(char num = '0'; num <= '9'; num=num+1) {
if(s.indexOf(num) != -1) return true;
}
return false; //none of them were found so we got here
}
public String checkNumbers(String text) {
return text.matches(".*\\d+.*") ? "yes" : "no";
}

Comparing String to int JAVA

I am trying to figure out how to make sure a String variable does not have a number as a string. I cannot Import anything.
I have tried
NameArray[i].equalsIgnoreCase("")) || Integer.parseInt(NameArray[i]) >= 48 && Integer.parseInt(NameArray[i]) < 58
but it did not work.
In Java 8+, you might use an IntStream to generate a range ([48, 58]) and then check if that as a String is equal to your NameArray. Something like,
if (IntStream.rangeClosed(48, 58).anyMatch(x -> String.valueOf(x)
.equals(NameArray[i]))) {
}
You mention that you want to make sure it doesn't contain a value - so perhaps you really want noneMatch like
if (IntStream.rangeClosed(48, 58).noneMatch(x -> String.valueOf(x)
.equals(NameArray[i]))) {
}
You can try converting string to number using Integer.parseInt(string).
If it gives an Exception than it is not a number.
public boolean validNumber(String number)
{
try
{
Integer.parseInt(number);
}
catch (NumberFormatException e)
{
return false;
}
return true;
}
So, you need to check for a string which doesn't contain any numbers.
Try using regex .*[0-9].* which will check for occurrence of any numerical character in your string.
String regex = ".*[0-9].*";
// Returns true
System.out.println("1".matches(regex));
System.out.println("100".matches(regex));
System.out.println("Stack 12 Overflow".matches(regex));
System.out.println("aa123bb".matches(regex));
// Returns false
System.out.println("Regex".matches(regex));
System.out.println("Java".matches(regex));

Verify if a String is an integer (numberFormatException)

I was trying to write a piece of code to test if a string contains an integer. I am aware of the try catch solution, but i have read it becomes bad if you call the method from other classes. What I have read is that the method will show the error, but the main of the class calling it will keep running anyway.
Therefore, I was trying to do it manually. My problem is that i am able to assess that the string is not empty and that all the characters in the string are digits, but I can't find a way to verify whether the number is too big to be sorted in an integer. Point is, i have found on stackoverflow many similar topics, but noone solve this problem without try catch.
Here is my method.
// INTEGER VERIFICATION
public static boolean isInteger (String str_input){
int number_of_digits = 0;
if (str_input.isEmpty()) {
JOptionPane.showMessageDialog(null, "No input inserted", "Error", JOptionPane.ERROR_MESSAGE);
return false;
}
for (char c : str_input.toCharArray()){
if(Character.isDigit(c)){
number_of_digits++;
}
}
if (number_of_digits == str_input.length()){
return true;
}
else {
JOptionPane.showMessageDialog(null, "The input is not an integer", "Error", JOptionPane.ERROR_MESSAGE);
return false;
}
}
Thanks in advance for your help!
I think the best way to do this is as pointed by Leo in the comments.
public static boolean isInteger(final String strInput) {
boolean ret = true;
try {
Integer.parseInt(strInput);
} catch (final NumberFormatException e) {
ret = false;
}
return ret;
}
Also I suggest you separate the GUI part from the checking method, let the caller decide what to do if false (for example, maybe in some situations you want to check if it's an integer but don't show the dialog).
You could modify your method to make sure the number fits within an int.
It can be done by parsing the input as long, and checking against the range of int numbers.
// INTEGER VERIFICATION
public static boolean isInteger (String str_input){
int number_of_digits = 0;
if (str_input.isEmpty()) {
JOptionPane.showMessageDialog(null, "No input inserted", "Error", JOptionPane.ERROR_MESSAGE);
return false;
}
for (char c : str_input.toCharArray()){
if(Character.isDigit(c)){
number_of_digits++;
}
}
if (number_of_digits == str_input.length()){
if (str_input.length > 15) // arbitrary length that is too long for int, but not too long for long
return false;
long number = Long.parseLong(str_input);
if (number > Integer.MAX_VALUE || number < Integer.MIN_VALUE)
return false;
else
return true;
}
else {
JOptionPane.showMessageDialog(null, "The input is not an integer", "Error", JOptionPane.ERROR_MESSAGE);
return false;
}
}
BTW, if you allow negative inputs, you should change your check to allow '-' as the first character.
That said, I agree with all the comments that say you'd be better off to just call Integer.parseInt() and catch the exception.
How about using Regex
-?\\d+(\\.\\d+)? which accept negative and decimal numbers
Source: http://www.vogella.com/tutorials/JavaRegularExpressions/article.html
public static boolean isNumeric(String str) {
return str.matches("-?\\d+(\\.\\d+)?");
}

Is there an existing library method that checks if a String is all upper case or lower case in Java?

I know there are plenty of upper() methods in Java and other frameworks like Apache commons lang, which convert a String to all upper case.
Are there any common libraries that provide a method like isUpper(String s) and isLower(String s), to check if all the characters in the String are upper or lower case?
EDIT:
Many good answers about converting to Upper and comparing to this. I guess I should have been a bit more specific, and said that I already had thought of that, but I was hoping to be able to use an existing method for this.
Good comment about possible inclusion of this in apache.commons.lang.StringUtils.
Someone has even submitted a patch (20090310). Hopefully we will see this soon.
https://issues.apache.org/jira/browse/LANG-471
EDIT:
What I needed this method for, was to capitalize names of hotels that sometimes came in all uppercase. I only wanted to capitalize them if they were all lower or upper case.
I did run in to the problems with non letter chars mentioned in some of the posts, and ended up doing something like this:
private static boolean isAllUpper(String s) {
for(char c : s.toCharArray()) {
if(Character.isLetter(c) && Character.isLowerCase(c)) {
return false;
}
}
return true;
}
This discussion and differing solutions (with different problems), clearly shows that there is a need for a good solid isAllUpper(String s) method in commons.lang
Until then I guess that the myString.toUpperCase().equals(myString) is the best way to go.
Now in StringUtils isAllUpperCase
This if condition can get the expected result:
String input = "ANYINPUT";
if(input.equals(input.toUpperCase())
{
// input is all upper case
}
else if (input.equals(input.toLowerCase())
{
// input is all lower case
}
else
{
// input is mixed case
}
Not a library function unfortunately, but it's fairly easy to roll your own. If efficiency is a concern, this might be faster than s.toUpperCase().equals(s) because it can bail out early.
public static boolean isUpperCase(String s)
{
for (int i=0; i<s.length(); i++)
{
if (!Character.isUpperCase(s.charAt(i)))
{
return false;
}
}
return true;
}
Edit: As other posters and commenters have noted, we need to consider the behaviour when the string contains non-letter characters: should isUpperCase("HELLO1") return true or false? The function above will return false because '1' is not an upper case character, but this is possibly not the behaviour you want. An alternative definition which would return true in this case would be:
public static boolean isUpperCase2(String s)
{
for (int i=0; i<s.length(); i++)
{
if (Character.isLowerCase(s.charAt(i)))
{
return false;
}
}
return true;
}
Not that i know.
You can copy the string and convert the copy to lower/upper case and compare to the original one.
Or create a loop which checks the single characters if the are lower or upper case.
This method might be faster than comparing a String to its upper-case version as it requires only 1 pass:
public static boolean isUpper(String s)
{
for(char c : s.toCharArray())
{
if(! Character.isUpperCase(c))
return false;
}
return true;
}
Please note that there might be some localization issues with different character sets. I don't have any first hand experience but I think there are some languages (like Turkish) where different lower case letters can map to the same upper case letter.
Guava's CharMatchers tend to offer very expressive and efficient solutions to this kind of problem.
CharMatcher.javaUpperCase().matchesAllOf("AAA"); // true
CharMatcher.javaUpperCase().matchesAllOf("A SENTENCE"); // false
CharMatcher.javaUpperCase().or(CharMatcher.whitespace()).matchesAllOf("A SENTENCE"); // true
CharMatcher.javaUpperCase().or(CharMatcher.javaLetter().negate()).matchesAllOf("A SENTENCE"); // true
CharMatcher.javaLowerCase().matchesNoneOf("A SENTENCE"); // true
A static import for com.google.common.base.CharMatcher.* can help make these more succinct.
javaLowerCase().matchesNoneOf("A SENTENCE"); // true
Try this, may help.
import java.util.regex.Pattern;
private static final String regex ="^[A-Z0-9]"; //alpha-numeric uppercase
public static boolean isUpperCase(String str){
return Pattern.compile(regex).matcher(str).find();
}
with this code, we just change the regex.
I realise that this question is quite old, but the accepted answer uses a deprecated API, and there's a question about how to do it using ICU4J. This is how I did it:
s.chars().filter(UCharacter::isLetter).allMatch(UCharacter::isUpperCase)
If you expect your input string to be short, you could go with myString.toUpperCase().equals(myString) as you suggested. It's short and expressive.
But you can also use streams:
boolean allUpper = myString.chars().noneMatch(Character::isLowerCase);
You can use java.lang.Character.isUpperCase()
Then you can easily write a method that check if your string is uppercase (with a simple loop).
Sending the message toUpperCase() to your string and then checking if the result is equal to your string will be probably slower.
Here's a solution I came up with that's a bit universal as it doesn't require any libraries or special imports, should work with any version of Java, requires only a single pass, and should be much faster than any regex based solutions:
public static final boolean isUnicaseString(String input) {
char[] carr = input.toCharArray();
// Get the index of the first letter
int i = 0;
for (; i < carr.length; i++) {
if (Character.isLetter(carr[i])) {
break;
}
}
// If we went all the way to the end above, then return true; no case at all is technically unicase
if (i == carr.length) {
return true;
}
// Determine if first letter is uppercase
boolean firstUpper = Character.isUpperCase(carr[i]);
for (; i < carr.length; i++) {
// Check each remaining letter, stopping when the case doesn't match the first
if (Character.isLetter(carr[i]) && Character.isUpperCase(carr[i]) != firstUpper) {
return false;
}
}
// If we didn't stop above, then it's unicase
return true;
}

Categories

Resources