-1

i'm working on my project in java, in my project i need to get input from some stream an to parse text and make it to generic char-by-char to some other types, one of them is "ValueNumber".

for that I'm using switch case

Now,because Number can start with ' - ' I need to check if the current char is a Digit between 0 to 9 or ' - ' or something else.

My question is how can I make some variable that will hold all the 10th digits by one variable ?

Shay Doron
  • 179
  • 2
  • 10

2 Answers2

0

String will hold it, or StringBuilder for better performance and then you can parse the string and see if it matches the regex:

return str.matches("[-]?[0-9]+");

if true, it is digit with or without negation sign, if false, it is not a digit you described. The digit can be as long as String allows.

Zeta Reticuli
  • 329
  • 2
  • 13
-1

I think you're imagining something like:

switch(aChar) {
   case '+':
       handlePlus();
       break;
   case ' ':
       handleSpace();
       break;
   case anyOf("-01234567890");
       handlePartOfNumber(aChar);
       break;
}

Unfortunately in Java, switch is not this sophisticated. switch deals with exact matches only.

You will need to use a series of if/else blocks instead:

if(aChar == '+') {
      handlePlus();
} else if(aChar == ' ') {
    handleSpace();
} else if(isMinusOrDigit(aChar)) {
    handlePartOfNumber(aChar);
}

Now, how do we implement isMinusOrDigit(char c)?

You've asked about "some variable that holds all the digits". Maybe you mean an array, or a List or a Set. I'll choose Set because it's the purest "bag of items, you don't care the order".

private static Set<Character> MINUS_AND_DIGITS = minusAndDigits();

private static Set<Character> minusAndDigits() {
    Set<Character> set = new HashSet<>();
    for(char c = '0'; c<='9'; c++) {
        set.add(c);
    }
    set.add('-');
}

private static boolean isMinusOrDigit(char c) {
    return MINUS_AND_DIGITS.contains(c);
}

You could also use

But in this case, you don't need a "multi value variable" to work out whether a character is a minus or a digit - because the number characters are next to each other in ASCII:

private static boolean isMinusOrDigit(char c) {
    return c == '-' || ( c >= 0 && c<=9 ); 
}
slim
  • 40,215
  • 13
  • 94
  • 127
  • You can't -- as explained in the answer. Use a chain of if/else statements instead. – slim Dec 13 '17 at 15:56