r/learnjava • • 2h ago

What is wrong with this code? MOOC.FI

So this piece of code is for finding the absolute value:

import java.util.Scanner;


public class AbsoluteValue {


    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
         int num = Integer.valueOf(scanner.nextLine());
         if(num < 0){
            num = (num*(-1));
         }
            System.out.println(num);
    }
}

But TMC MOOC.FI is showing this error:

TestMyCode
Some tests failed on the server

Need help?

Points: 0.00%

...

x

Test passed!

AbsoluteValueTest absolute ValueOfNegativeThree

Test passed!

AbsoluteValueTest absoluteValueOfSix
1 Upvotes

5 comments sorted by

View all comments

1

u/T_Caf 1h ago

It looks like the System.out.println() is outside the code block if you have a negative integer input, making it unable to find the absolute value for a negative integer. spoiler hint: You could use absolute value function to the input (regard less if it is pos or neg) and print that out

•

u/UpriseDaGr8 58m ago

Thanks for the suggestion! But, System.out.println()  is intentionally outside the "if" block so that if the number is negative, it gets converted to a positive number, and if its already positive, it gets printed directly.

•

u/T_Caf 45m ago

Understandable, and I see where you're going, kudos for that. I think it is just a bit difficult to get the absolute value,for negative integer, to print because that value does not appear to reach the print statement. May I suggest a second System.out.println within the if code block?