mercredi 1 septembre 2021

Why is my program not terminating? (Using while loop & if statements)

I'm working on a program for my class that takes in two numbers (both being a power of two) and outputs a set of functions. At the moment I have a method that checks to see if the number is a power of two (seems to be working) and two loops that prompt the user again if their input is invalid.

I'm not sure what the problem here is, but when I input an invalid number (ex: 5) the loop executes and it prompts me to enter another number. On the other hand, if I enter a valid number (ex: 64) it will continue running infinitely while displaying nothing (it's supposed to ask me for the second number). How can I make the rest of my code run?

Thank you!

    Scanner in = new Scanner(System.in);
    
    System.out.print("Enter a value for n that is a power of 2:  ");
    int num1 = in.nextInt();
    System.out.println("");

    
    //checks if # is power of 2, if not then user is prompted again
    while (isPowerOf2(num1) == false){
        
        if (isPowerOf2(num1) == false){
         System.out.println("ERROR Number is not a power of 2.\n");
         System.out.print("Enter a value for n that is a power of 2:  ");
         num1 = in.nextInt();
         System.out.println("");
        }else{
            break; 
        }

    }
    
    
    System.out.print("Enter a value for n that is a power of 2:  ");
    int num2 = in.nextInt();
    System.out.println("");
    
    
    
    while (isPowerOf2(num2) == false){
        
        if (isPowerOf2(num2) == false){
         System.out.println("ERROR Number is not a power of 2.\n");
         System.out.print("Enter a value for n that is a power of 2:  ");
         num2 = in.nextInt();
         System.out.println("");
        }else{
            break; 
        }
        
    }        

isPowerOf2:

    public static boolean isPowerOf2(double n){
        
        while(n%2 == 0){
            double temp1 = n;
            temp1 = temp1/2.0;
        }
            if(n == 1){
                return true;
            }else{
                return false;
            }
        
    }
    

Aucun commentaire:

Enregistrer un commentaire