0

I think I just broke Java...

public class Numbers { public static void main(String[] args) { int ten = 10; int five = 5; int result = 0; sum(ten, five, result); difference(ten, five, result); } public static void sum(int five, int ten, int addMainVars ) { addMainVars = ten + five; System.out.println("10 + 5 is " + addMainVars + "."); } public static void difference(int five, int ten, int subtractMainVars ) { subtractMainVars = ten - five; System.out.println("10 - 5 is " + subtractMainVars + "."); } } Pay attention to method difference(). The System.out.println is supposed to display "10 - 5 is 5." Instead, it writes "10 - 5 is -5." However, when I assign variable subtractMainVars a value of "five - ten," the System.out.println displays "10 - 5 is 5." This is what I want displayed, but I need to have subtractMainVars assigned "ten - five." Please help. Thank you.

11th Aug 2018, 2:57 PM
Fleet
Fleet - avatar
3 Answers
+ 2
Darn it! you nailed me good XD
13th Aug 2018, 1:49 AM
Ipang
+ 1
No you didn't, you just passed the arguments in wrong order, see, your call to difference method in main goes like this: difference(ten, five, result); But, definition for difference method is: public static void difference(int five, int ten, int subtractMainVars) { subtractMainVars = ten - five; // more codes here ... Here 'five' = 10, and 'ten' = 5 (see your method call in main). So, what happened here actually is, you are doing 5 - 10, which yields -5. Solution: Either swap the order of the 'five' and 'ten' parameters in difference method, or, don't change it, but swap ten and five in difference call in main. Hth, cmiiw
11th Aug 2018, 4:47 PM
Ipang
+ 1
Thank you very much. This helps a lot. I didn't actually feel that I broke Java, it was just click-bait. I appreciate the help!
12th Aug 2018, 9:16 PM
Fleet
Fleet - avatar