I can\'t figure out why it\'s always returning the value of arg1. I\'m building a weight converter.
public double convert(double arg1,int arg2,int arg3) {
//
rewrite every case like this
case 2: switch(arg3) { // if ounce
case 0: answer = (arg1 * ounce) / milligram;break;
case 1: answer = (arg1 * ounce) / gram;break;
case 2: answer = (arg1 * ounce) / ounce;break;
case 3: answer = (arg1 * ounce) / pound;break;
You should be using break
in switch statements,else your result may get detoriated
Other than using break
, using return
statements does the trick as well as it also prevents falling through cases.
case 2: switch(arg3) { // if ounce
case 0: return (arg1 * milligram) / milligram;
Nested case statements are pretty hard to read, and tough to debug. It'd be a better idea to encapsulate the functionality you need into a method call instead.
That being said, there's no break
statement anywhere in your switch. Regardless of the case, it will fall through to the last case (setting answer equal to the bottom of the case).
You are missing break
statements:
case 0:
answer = (arg1 * milligram) / milligram;
break;
...