0

Sorry im just learning java and im new to coding! The task of my code is to evaluate input in terms of odd and even numbers. Without the math.abs line the code would not recognize the odd/even values of negative numbers correctly.

i made a fix using the math.abs command to convert the negative value and get the desired result. But, i just wanted to know why this step is necessary and how java scanner interprets the negative value/symbol and provides the wrong answer without my fix.

import java.util.Scanner;

public class EvenOrOdd {

    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);

        System.out.print("Type a number: ");
        int x = Integer.parseInt(reader.nextLine());
        int f = Math.abs(x);

        if ( f % 2 == 1){
            System.out.println("The number is odd.");
        }
        else {
            System.out.println("The number is even.");
        }
    }
}
Balderk
  • 167
  • 10

1 Answers1

0

The remainder of a negative number divided by a positive number will be negative.

-1 % 2  

is

-1

but since that is not 1, you will declare it to be even.