Asked  7 Months ago    Answers:  5   Viewed   35 times

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.

 Answers

79

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;
}
Tuesday, June 1, 2021
 
Gigamegs
answered 7 Months ago
32

If you're using Java 5 or higher, you can use String.format:

urlString += String.format("u1=%s;u2=%s;u3=%s;u4=%s;", u1, u2, u3, u4);

See Formatter for details.

Thursday, June 3, 2021
 
sholsinger
answered 7 Months ago
15

Don't use atoi and atof as these functions return 0 on failure. Last time I checked 0 is a valid integer and float, therefore no use for determining type.

use the strto{l,ul,ull,ll,d} functions, as these set errno on failure, and also report where the converted data ended.

strtoul: http://www.opengroup.org/onlinepubs/007908799/xsh/strtoul.html

this example assumes that the string contains a single value to be converted.

#include <errno.h>

char* to_convert = "some string";
char* p = to_convert;
errno = 0;
unsigned long val = strtoul(to_convert, &p, 10);
if (errno != 0)
    // conversion failed (EINVAL, ERANGE)
if (to_convert == p)
    // conversion failed (no characters consumed)
if (*p != 0)
    // conversion failed (trailing data)

Thanks to Jonathan Leffler for pointing out that I forgot to set errno to 0 first.

Tuesday, August 10, 2021
 
edsk
answered 4 Months ago
17

You can either convert your numbers into a string using the toString or valueOf methods of the wrapper classes (guess you are not there yet), or just stuff all your primitives into the printline without the String output.

system.out.println(h + three + one + ten + " " + "w" + zero + "r" + won + "d " + two + " " + t);

All you need to look for is that there is a String in the printline statement. Meaning if you only want to print our number based datatype you can use system.out.println("" + youNumberVariable).

There would also be the option to add an empty string at the beginning of your declaration of output output = "" + theRest; to force all following values into the string like it does in the printline statement.

Most of it is not very pretty coding but will completly suffice for the learning process.

Tuesday, August 24, 2021
 
Drazisil
answered 4 Months ago
26
return Math.Truncate(number) == number;

As mentioned in the comments, you might need to take account of the fact that a double representation of your number might not be an exact integer. In that case you'll need to allow for some margin-of-error:

double diff = Math.Abs(Math.Truncate(number) - number);
return (diff < 0.0000001) || (diff > 0.9999999);
Thursday, October 7, 2021
 
Tapha
answered 2 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :
 
Share