1

i am new to java, trying to write my first app - calculator - on my own. Tried searching around, but couldn't find anything similar. Could it be done through ASCII or bytes? To simplify what i want to know i give the following example:

char ch = '+';
int i = 1 ch 2;
int = 3;

I want to somehow convert char + to an actual + sign for int calculation to work. Is it possible? Thank you in advance!

Deividas Strioga
  • 1,467
  • 16
  • 24

2 Answers2

3

This is not possible. You will need to check the value of the char variable at runtime.

int a = 1, b = 2, result = 0;

switch(ch) {
    case '+':
        result = a + b;
        break;
    case '-':
        result = a - b;
        break;
    // et.c
}

// The result of the calculation is now in `result`
SamTebbs33
  • 5,507
  • 3
  • 22
  • 44
-1
Character.getNumericValue(c)

The java.lang.Character.getNumericValue(char ch) returns the int value that the specified Unicode character represents. For example, the character '\u216C' (the roman numeral fifty) will return an int with a value of 50.

The letters A-Z in their uppercase ('\u0041' through '\u005A'), lowercase ('\u0061' through '\u007A'), and full width variant ('\uFF21' through '\uFF3A' and '\uFF41' through '\uFF5A') forms have numeric values from 10 through 35. This is independent of the Unicode specification, which does not assign numeric values to these char values.

This method returns the numeric value of the character, as a nonnegative int value;

-2 if the character has a numeric value that is not a nonnegative integer;

-1 if the character has no numeric value.

suulisin
  • 1,414
  • 1
  • 10
  • 17