Is it possible to solve this sumDouble problem with an if else function?

33 Views Asked by At

My practice problem is

Given two int values, return their sum. Unless the two values are the same, then return double their sum.

sumDouble(1, 2) → 3 sumDouble(3, 2) → 5 sumDouble(2, 2) → 8

My first thought was to write a if else function, so I wrote

public int sumDouble(int a, int b) {
  if (int a == int b){
   return sum (int a * int b);
 } else {
   return sum (int a + int b);
 };
}

The thought process behind this was that if int a and int b was equal to each other, then I would return the sum of them multiplied by each other, if not then return the sum of them adding each other.

A problem I am running into is that on line 3, i get an error of ".class" What does this mean?

1

There are 1 best solutions below

1
Bohemian On

You have some basic syntax and logic errors. Try this:

public int sumDouble(int a, int b) {
    if (a == b) {
        return (a + b) * 2;
    }
    return a + b;
}

btw, it can be done in 1 line:

public int sumDouble(int a, int b) {
    return (a == b ? 2 : 1) * (a + b);
}