tags:

views:

159

answers:

4

Given a string

7 + 45 * 65

How to check whether a given character of this string is an integer and then store the whole integer value in an integer variable?

E.g. for 65, check if 6 is an integer, if yes, then store 65 in another integer variable. You can assume that the string can be converted into a character array.

+1  A: 

Check out this post on exactly the same topic:

Java Programming - Evaluate String math expression

It looks like BeanShell has the cleanest method to do what you need. You could also try the JavaScript Engine method (although BeanShell looks much cleaner to me).

Justin Niessner
+1  A: 

Given that this looks like homework below are some tips for a simple way to parse and store each integer value.

  • Check out the API documentation for the Character class. This will contain methods for determining whether a character is a digit.
  • Consider using a StringBuilder to store the intermediate numerical result as you read in each digit of the number.
  • Check the Integer class API for methods to help with parsing the String value (stored within your StringBuilder) and turning it into an int.
  • Finally, consider using a List (e.g. LinkedList) to store the int value.
Adamski
+1  A: 

Easiest solution would be to use java.util.Scanner. You can set Scanner.useDelimeter("\\D+") which will mean skip any non-digit characters, and then call Scanner.nextInt() to get next Integer from the String.

If you want to work with characters, then use Character.isDigit(char c).

tulskiy
Your answer was good but i didnt used it .. but its perfectly right and ill use it in future .. thans
D.J.
A: 

For a quick and dirty soluiton I would use StringTokenizer and try { Integer.parseInt() } catch (NumberFormatException){}

Chris Nava