开发者

Arithmetic in java

I have the following homework problem:

开发者_如何学Go

Write an application integer on that reads an integer and determines and prints whether it is odd or even.


Use the Scanner class for reading input.

Store that input into an integer. Check if input is really a valid integer. Otherwise, throw an exception.

Afterwards, use the modulo operator to check if it's odd or even.

Use System.out.println to print if it's odd or even.


public static void main(String[] args) {

    System.out.println("Enter number");

    Scanner sc = new Scanner(System.in);

    try {

        int i = sc.nextInt();
        if (Math.abs(i) / i == 1) {
            if ((Math.abs(i) % 2) == 0) {
                System.out.println("Even");
            } else {
                System.out.println("Odd");
            }
        }

    } catch (Exception ex) {
        System.out.println("Exception " + ex.toString());
    }

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜