mercredi 8 avril 2020

using if else statement to scan and print odd and even numbers

I am having a problem with this if else statement. The requirement is:

  • If n is odd, print Weird
  • If n is even and in the inclusive range of 2 to 5, print Not Weird
  • If n is even and in the inclusive range of 6 to 20, print Weird
  • If n is even and greater than 20, print Not Weird.

When the input number is 18 the output is expected to be Weird. Same for the input number 20.

    import java.util.*;

public class Solution {
    public static final Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        int N = scanner.nextInt();
        scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

        scanner.close();

        String ans = "";

        if ((N % 2) == 1) {
            ans += "Weird";
            System.out.println(ans);
        } 
        else if ((N % 2) == 0) {
            if (N >= 2 || N <= 5) {
                ans += "Not Weird";
                System.out.println(ans);
            }
        } 
        else if ((N % 2) == 0) {
            if (N >= 6 || N <= 20) {
                ans += "Weird";
                System.out.println(ans);
            }
        } 
        else if ((N % 2) == 0) {
            if (N > 20) {
                ans += "Not Weird";
                System.out.println(ans);
            }
        }
    }
}

Edit: But when I input the number 18 instead of Weird the output comes as Not Weird., same for number 20.

Aucun commentaire:

Enregistrer un commentaire