lundi 1 août 2016

Local variable manipulated in if statement can't be accessed from within the scope. Why?

First, I calculate whether num is a power of 2.

If it is, then I set flag to true, otherwise, to false.

But the Problem is I can't access that flag from outside the condition.. You've gotta help me.. Thanks

public  static void main(String[] args){
    Scanner scan = new Scanner(System.in);
    System.out.print("Enter a number to check if it's a POWER 2 : ");
    int num = scan.nextInt();     // input from user
    boolean flag = false;         // check to see if it is a power 2

    for(int i = 0; i < num/2;i++){
        if(num==Math.pow(i,2)) {
            flag = true;
            break;
        }
    }

    if(flag)
        System.out.println("It's power of 2");
    else
        System.out.println("It's not power of 2");

}

Aucun commentaire:

Enregistrer un commentaire