r/learnjava • • 12h 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
2 Upvotes

8 comments sorted by

View all comments

0

u/T_Caf 11h 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

1

u/UpriseDaGr8 10h 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.

0

u/T_Caf 10h 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?

1

u/UpriseDaGr8 9h ago

It was just some indentation error in the end 😅. Thanks for the suggestions tho!