Why does my program return nothing?

I just started learning java and for some reason my program returns nothing when it compiles.

Goal: 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

Problem can also be found from here

my code:

public class Test{
   public static void main(String[] Args){
      printPowersOf2(3);
      printPowersOf2(10);           
    }
    public static int printPowersOf2(int num){
      double b = Math.pow(2,num);
      int a = (int)b;
      return a;
    }
}

Answer

It does returns the value but this is not what you want. You would like to print it! You should print the values in a loop using:

System.out.printf("%d ", a);

instead of return a; The full function:

public static void printPowersOf2(int num) {
    for (int i = 0; i < num; i++) {
        System.out.print("%d ", Math.pow(2, i));
    }
    System.out.println(); // for the line break
}

No need for doubles, as these numbers are perfect squares.

Leave a Reply

Your email address will not be published. Required fields are marked *