How to Add Two Java.Lang.Numbers

How to add two java.lang.Numbers?

You say you don't know if your numbers are integer or float... when you use the Number class, the compiler also doesn't know if your numbers are integers, floats or some other thing. As a result, the basic math operators like + and - don't work; the computer wouldn't know how to handle the values.

START EDIT

Based on the discussion, I thought an example might help. Computers store floating point numbers as two parts, a coefficient and an exponent. So, in a theoretical system, 001110 might be broken up as 0011 10, or 32 = 9. But positive integers store numbers as binary, so 001110 could also mean 2 + 4 + 8 = 14. When you use the class Number, you're telling the computer you don't know if the number is a float or an int or what, so it knows it has 001110 but it doesn't know if that means 9 or 14 or some other value.

END EDIT

What you can do is make a little assumption and convert to one of the types to do the math. So you could have

Number c = a.intValue() + b.intValue();

which you might as well turn into

Integer c = a.intValue() + b.intValue();

if you're willing to suffer some rounding error, or

Float c = a.floatValue() + b.floatValue();

if you suspect that you're not dealing with integers and are okay with possible minor precision issues. Or, if you'd rather take a small performance blow instead of that error,

BigDecimal c = new BigDecimal(a.floatValue()).add(new BigDecimal(b.floatValue()));

Add two numbers without knowing exact type in Java

You can invoke Number.doubleValue() and add:

Number n1 = new Double(10.3d);
Number n2 = new Integer(12);
System.out.println(n1.doubleValue() + n2.doubleValue());

Addition of two given numbers

I saw your code and and the resultant sum 1150 does contain 1's and 0's.

s.contains(x); 

This function only checks if the string contains the value x or not. Since "1150" contains both 1's and 0's therefore your function prints the wrong output.

One way of solving this problem would be to add the two numbers and then check the resultant sum digit by digit. You can make a function that will do that for you.

public void checkOnesAndZeros(int resultantSum) {
while (resultantSum > 0) {
int remainder = resultantSum % 10;
if(remainder != 1 && remainder != 0) {
System.out.println("The addition does not have only 1’s and 0’s.");
return;
}
resultantSum = resultantSum / 10;
}
System.out.println("The addition only has 1’s and 0’s");
}

Add two numbers instead of combining

You are using num1 and num2 which are Strings instead of ans which should be your sum as an int.
Also you don't add correctly the 2 values into ans.

public static void main(String args[]){
String num1 = JOptionPane.showInputDialog(null,"Enter a number");
String num2 = JOptionPane.showInputDialog(null,"Enter another number");

int ans = Integer.parseInt(num1);
ans += Integer.parseInt(num2);

JOptionPane.showMessageDialog(null,"Your answer is " + ans);
}

adding two very large numbers

Sounds like you want to use BigInteger


[edit] To pass a number larger than Integer.MAX_VALUE to the constructor, use a long:

new BigInteger(9876543210L)

If you need a number larger than a long can hold, you'll need to find some other way of constructing it (like passing it in as a string, or multiplying two BigIntegers).

How can I add any set of Java Number objects, getting the most accurate result?

There is no nice way to do this, but you can break it up into a lot of smaller, simpler methods. My approach is to set up a hierarchy of types. Ideally the addition would only involve types with lower ranks. Once you've worked out the appropriate level to do the addition at, you can call the appropriate method. Here is my code (not tested).

private static final Map<Class<? extends Number>, Integer> RANKS;

static {
Map<Class<? extends Number>, Integer> map = new IdentityHashMap<>();
map.put(Byte.class, 0);
map.put(Short.class, 1);
map.put(Integer.class, 2);
map.put(Long.class, 3);
map.put(BigInteger.class, 4);
map.put(Float.class, 5);
map.put(Double.class, 6);
map.put(BigDecimal.class, 7);
RANKS = Collections.unmodifiableMap(map);
}

private static Number addBytes(Number... numbers) {
byte a = 0;
for (Number number : numbers)
a += number.byteValue();
return a;
}

private static Number addShorts(Number... numbers) {
short a = 0;
for (Number number : numbers)
a += number.shortValue();
return a;
}

private static Number addInts(Number... numbers) {
int a = 0;
for (Number number : numbers)
a += number.intValue();
return a;
}

private static Number addLongs(Number... numbers) {
long a = 0;
for (Number number : numbers)
a += number.longValue();
return a;
}

private static Number addBigIntegers(Number... numbers) {
BigInteger a = BigInteger.ZERO;
for (Number number : numbers)
a = a.add(number instanceof BigInteger ? (BigInteger) number : BigInteger.valueOf(number.longValue()));
return a;
}

private static Number addFloats(Number... numbers) {
float a = 0;
for (Number number : numbers)
a += number.floatValue();
return a;
}

private static Number addDoubles(Number... numbers) {
double a = 0;
for (Number number : numbers)
a += number.doubleValue();
return a;
}

private static Number addBigDecimals(Number... numbers) {
BigDecimal a = BigDecimal.ZERO;
for (Number number : numbers) {
a = a.add(
number instanceof BigDecimal ? (BigDecimal) number
: number instanceof BigInteger ? new BigDecimal((BigInteger) number)
: new BigDecimal(number.doubleValue()));
}
return a;
}

public static Number add(Number... numbers) {
if (numbers.length == 0)
return 0;
int max = -1;
for (Number number : numbers) {
Integer rank = RANKS.get(number.getClass());
if (rank == null)
throw new IllegalArgumentException();
max = Math.max(max, rank);
}
switch (max) {
case 0: return addBytes(numbers);
case 1: return addShorts(numbers);
case 2: return addInts(numbers);
case 3: return addLongs(numbers);
case 4: return addBigIntegers(numbers);
case 5: return addFloats(numbers);
case 6: return addDoubles(numbers);
case 7: return addBigDecimals(numbers);
default: throw new IllegalStateException();
}
}


Related Topics



Leave a reply



Submit