티스토리 뷰

JAVA

Nested if-else example

seoca 2019. 1. 2. 08:37



Nested If-Else


To avoid duplicated conditions and to make decisions in your program, the nested structure could be considered as a big frame of the program using If-Else statement.


if else 로 문제를 접근할 때 중복조건을 피하고 우선순위를 정하기 위해 상위 하위에 속하는 구조(nested If-Else)를 먼저 파악한 후 틀을 잡고 문제를 해결 해 나갈 것! 




Q. 

Given an integer, , perform the following conditional actions:

  • If  is odd, print Weird
  • If  is even and in the inclusive range of  to , print Not Weird
  • If  is even and in the inclusive range of  to , print Weird
  • If  is even and greater than , print Not Weird

Complete the stub code provided in your editor to print whether or not  is weird.

Input Format

A single line containing a positive integer, .

Constraints



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class Solution {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int n=sc.nextInt();            
        String ans=""; // String initilization
        if(n>=1 && n<=100){ // 1 to 100 (the condition that should be covered for every conditions.)
            if(n%2==1){ //odd numbers
                ans = "Weird";
            }
            else{ //even numbers
                if(n>=2 && n<=5 ){ // other conditions
                   ans= "Not Weird";
                }
                else if (n>=6 && n<=20){
                    ans = "Weird";
                }
                else if(n>20) {
                    ans = "Not Weird";
                }
            }
        }
        else{
            ans="Invalid no! Enter a number between 1 and 100.";
        }
        System.out.println(ans);
    }
}

 cs





Reference

Hackerrank (https://www.hackerrank.com/)

w3schools (www.w3schools.com)




'JAVA' 카테고리의 다른 글

Inheritance  (0) 2019.01.03
Constructor in Java  (0) 2019.01.02
instance in Java  (0) 2018.12.31
main method in Java  (0) 2018.12.31
Java Data type (primitive & non-primitive)  (0) 2018.12.18