Search code examples
javaconverterszeronegative-number

Java Convert negative numbers to 0


I am having issues with this code and can't figure out the issue, I know it's a logical error but I can't seem to figure it out, all results end up as 0.

Code:

import java.util.Scanner;

public class ConvertNegative {
   public static void main (String [] args) {
      int userNum = 0;

      if (userNum >= 0)
         System.out.println("Non-negative");
      else
         System.out.println("Negative; converting to 0");
         userNum = 0;
         System.out.format("Final: %d", userNum);
         System.out.println(""); 

      return;
   }
}

I'd appreciate any help, thanks.


Solution

  • If you have multi line conditions / for loops you need to set brackets. Without the brackets your else block would just execute the first statement after it. In your case the System.out.println("Negative; converting to 0");. In any case your variable userName would be set to 0 as the following line wouldn't be part of the else block anymore. More than 1 line = brackets.

    public class ConvertNegative {
        public static void main (String [] args) {
            int userNum = 0;
    
            if (userNum >= 0)
                System.out.println("Non-negative");
            else{
                System.out.println("Negative; converting to 0");
                userNum = 0;
                System.out.format("Final: %d", userNum);
                System.out.println(""); 
            }
            //return; -> There is no need for the return as the main method has no return value.
        }
    }