Search code examples
javaandroidcharsequence

Android CharSequence Number Detection(0-9) in one statement without using if else


I am new in android and trying to make a calculator...

Now i have extracted whole expression in a charSequence variable.

e.g 30+69-(3-10)

Now i need to detect whether the first character of charSequence variable is either a number (0-9) or a character/operator.

i can use get.subSequence(0,1) but dont want to compare it with every number to decide whether its a number or not and if its a number then which one it is....

How can i compare it with every number using fewer conditions and also extract that specific number....


Solution

  • You can use:

    Character.isDigit(someChar)
    

    This will tell you if a char is a number or not.

    If it is not, you can assume it is an operator and treat it as such.

    So an implementation could look like:

    CharSequence chars = "1+2-3";
    
    for(int i = 0; i < chars.length(); i++ ) {
        if (Character.isDigit(chars.charAt(i))) {
            //is digit
        } else {
            //is operator
        }
    }
    

    *I don't have a java compiler available, so I cant promise that works at the moment.