0

Write a method called printPowersOf2 that accepts a maximum number as an argument and prints each power of 2 from 20 (1) up to that maximum power, inclusive. For example, consider the following calls: printPowersOf2(3); printPowersOf2(10); These calls should produce the following output:

1 2 4 8

1 2 4 8 16 32 64 128 256 512 1024

yes, this is a homework problem and I am sorry. I am not asking for code or anything just a little guidance would be helpful and I want to know what I am doing is wrong. Thank You.

import java.lang.Math;

public class Power {

    public void printPowersOf2(double thisX){

        double k = 1.0;

        for(double i = k; i <= Math.pow(2,thisX); i++){

             double square = k;

             System.out.print(square+" ");

             k = 2.0 * k;

        }
    }
}

Second Class:

import java.util.*;

public class PowerMain{
    public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        System.out.println("Please, enter a number you want to square: ");
        double exponents = input.nextDouble();
        Power numberOfPower = new Power();
        numberOfPower.printPowersOf2(exponents);
    }
}

My output = 1.0 2.0 4.0 8.0 16.0 32.0 64.0 128.0 > when i enter 3

Daniel Stanley
  • 1,050
  • 6
  • 15
happy face
  • 43
  • 9

2 Answers2

0

You want to get the power of 2 for each number 0 to thisX so you should change your loop like:

for(double i = 0; i <= thisX; i++)

You should be looping from 0 to your number adding 1 each loop and for each iteration take that number ^ 2 like 0^2 print 1^2 print 2^2 print 3^2 print...

brso05
  • 13,142
  • 2
  • 21
  • 40
0

Your issue is the line

for(double i = k; i <= Math.pow(2,thisX); i++)

The reason why is because the following code produces the value 8 when the input is 3

Math.pow(2,thisX)

If you notice, you have 8 output values which comes from 2^3. You should just be looping 3 times (instead of your current 8), so you should really just do the following

for(int i = 0; i < thisX; i++)
...
dsingleton
  • 976
  • 6
  • 7