Cast
Cast

Reputation: 61

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;
    }
}

Upvotes: 0

Views: 509

Answers (2)

shauryachats
shauryachats

Reputation: 10385

I think your code should be:

public class Test{
   public static void main(String[] Args){
      printPowersOf2(3);
      printPowersOf2(10);           
    }
    public static void printPowersOf2(int num){
      for(int i = 0; i <= num; ++i)
      {
          double b = Math.pow(2,num);
          System.out.print(b + " ");
      }
    }
}

You do not have to return anything. You have to print inside the function only.

Upvotes: 1

meskobalazs
meskobalazs

Reputation: 16041

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.

Upvotes: 3

Related Questions