Is it possible to use a char as an arithmetic operator?
Is there some kind of conversion of the char that has to take place first?
For example:
Code:char addIt = '+';
int a, b, c;
a = 5;
b = 3;
c = a addIt b;
Printable View
Is it possible to use a char as an arithmetic operator?
Is there some kind of conversion of the char that has to take place first?
For example:
Code:char addIt = '+';
int a, b, c;
a = 5;
b = 3;
c = a addIt b;
Not the way you're trying to use it. It's possible to map a Character to a binary method and use that method to do the calculation you desire.
It won't be nearly as clean looking. If you want operator overload, you'll need to learn C++.
For example:
Code:import java.util.HashMap;
import java.util.Map;
public class TestBinaryMethod
{
public static Map<Character, BinaryMethod> methodMap = new HashMap<Character, BinaryMethod>();
public static void fillMap()
{
methodMap.put('+', new BinaryMethod()
{
public double execute(double d1, double d2)
{
return d1 + d2;
}
});
methodMap.put('-', new BinaryMethod()
{
public double execute(double d1, double d2)
{
return d1 - d2;
}
});
}
public static void main(String[] args)
{
fillMap();
System.out.println(methodMap.get('+').execute(100, 40));
System.out.println(methodMap.get('-').execute(100, 40));
}
}
interface BinaryMethod
{
public double execute(double d1, double d2);
}
char is a primitive type that represents a two-byte Unicode character.
Character is an object wrapper around the primitive type.
The Character class has various means of obtaining an integer representation of Unicode characters (code points), which can then be converted back to char.