0

I'm trying to determine if a number is an integer in an expression like this. (10 * 2) + 5. If the expression was (10 * 2) + 5.24 I want the program to say that there's a non-integer in that expression. Current code:

public static boolean isInt(String expr) {
    for (int i = 0; i<expr.length(); i++){
        if (expr. charAt(i) != (int)i){
        return false;
        }
    }
    return true;
}

The problem is that there are a lot more characters besides just numbers. So I want it to just check the numbers and ignore all the other symbols to determine if every number in the string is an integer.

davepmiller
  • 2,620
  • 3
  • 33
  • 61
John Kyle
  • 117
  • 2
  • 8
  • if (expr.contains (".")) – Scary Wombat Mar 19 '15 at 00:36
  • Does the expression will have only numbers, and other characters like ()+*, right? Or wrong inputs(alphabets) also? – RahulArackal Mar 19 '15 at 00:45
  • To evaluate a numerical expression including mathematical operations try using the ScriptEngine class as shown in the green arrow reply at http://stackoverflow.com/questions/2605032/is-there-an-eval-function-in-java. To use Java to evaluate it would involve writing a class that does it to an external file, then compiling and running its jar as an external executable. –  Mar 19 '15 at 01:07
  • If you find any of these resolve your problem, you should mark it as answer. – senderj Mar 20 '15 at 06:05

3 Answers3

0

I would start by tokenizing into "words", splitting on * /+-()^ and blank spaces. The results should just be numbers, if I understand what you're doing.

To split using Guava: Iterable tokens = Splitter.on(CharMatcher.anyOf("- /*+()^")).split(myExpression);

Then you can scan the "words" looking for a decimal point as suggested by @Scary Wombat

Here is a complete version:

public void test() {

    char[] values = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
    List<Character> ints = Chars.asList(values);

    String str = "the values are 4 and 4.03 tons";
    Iterable<String> tokens = Splitter.on(CharMatcher.anyOf("- /*+()^")).split(str);

    for (String token : tokens) {
        char[] chars = token.toCharArray();
        for (char c : chars) {
            if (!ints.contains(c)) {
                System.out.println(token + " is not an int");
                break;
            }
        }
    }
}

Producing:

the is not an int
values is not an int
are is not an int
and is not an int
4.03 is not an int
tons is not an int
L. Blanc
  • 2,150
  • 2
  • 21
  • 31
0

See if this can meet your needs

String str = "the values are 4 and 4.03 tons";
Pattern p = Pattern.compile("\\d+[.]?\\d*");
Matcher m = p.matcher(str);
while (m.find()) {
    String ss = m.group();
    int temp_i;
    try {
        temp_i = Integer.parseInt(ss);
        System.out.println(temp_i);
    } catch (NumberFormatException nfe) {
        System.out.println(String.format("%s not integer", ss));
    }//end try
}//end while

Or, to cater for float such as 3e-2, use

Pattern p = Pattern.compile("\\d+[.eE]?[-]?\\d*");

Hope it helps.

senderj
  • 400
  • 1
  • 9
0

We can achieve it with reg expression.

String regExp = "([0-9]*\\.[0-9]*)";

And then count the no: of matches with each equality found.

So, the complete code is here:

import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class RegExpDemo {
    public static void main(String[] args) {
        String regExp = "([0-9]*\\.[0-9]*)";
        String input = "-1 + 5 - (10 * 2) + 5.24 / (3.146 * 22 / 100)";
        try {
            Pattern pattern = Pattern.compile(regExp);
            Matcher matcher = pattern.matcher(input);
            int count = 0;
            while(matcher.find()) {
                System.out.println("Result "+matcher.group());
                count++;
                //System.out.println("Count "+matcher.groupCount());    
            }   
            System.out.println("Total Count "+count);           
        } catch(Exception exp) {
            System.out.println(exp);
        }
    }
}
O/p
--------------
Result 5.24
Result 3.146
Total Count 2

I hope the input contains only valid number formats and any other characters are not used. ie; 1,26 instead of 1.26. If any other characters, you may need to modify the pattern depending on that

Also if you need to count values like 1..26 then use quantifier + with .(dot)

        String regExp = "([0-9]*\\.+[0-9]*)";
        String input = "-1 + 5 - (10 * 2) + 5.24 / (3.146 * 22 / 100) - 1..26";
RahulArackal
  • 944
  • 12
  • 28