-4

I need replace the while loop with a for loop. Make sure it produces the same output, if 6 is given as a parameter: java PowersOfTwo 6. But my answer cannot run well. Always outputs:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0

Below is the previous example:

public class PowersOfTwo {
    public static void main(String[] args) {
        int N = Integer.parseInt(args[0]); // last power of two to print
        int i = 0; // loop control counter
        int v = 1; // current power of two
        while (i <= N) {
            System.out.println(i + " " + v);
            i = i + 1;
            v = 2 * v;
        }
    }
}

Below is my answer:

public class PowersOfTwo {
    public static void main(String[] args) {
        int N = Integer.parseInt(args[0]); // last power of two to print
        int v = 1; // current power of two
        for (int i = 0; i <= N; i ++) {
            System.out.println(i + " " + v);    
            i = i + 1;
            v = 2 * v;
        }
    }
}
xlm
  • 6,854
  • 14
  • 53
  • 55
Auck
  • 49
  • 1
  • 6

3 Answers3

2

I strongly suggest you to use a tool like this - it helps in the majority of cases similar to yours.

java.lang.ArrayIndexOutOfBoundsException: 0 occurs when trying to iterate an empty array - so check if you pass the params into app properly and didn't forget 6 here:

 java PowersOfTwo 6

Also I suppose you should remove the i = i + 1; line.

Anton Hlinisty
  • 1,441
  • 1
  • 20
  • 35
1

You can use , to separate multiple variables (and increment commands). So you could do something like,

for (int i = 0, v = 1; i <= N; i++, v *= 2) {
    System.out.println(i + " " + v);
}

Finally, when you run the program, pass the value N.

java -cp . PowersOfTwo 4

Which outputs

0 1
1 2
2 4
3 8
4 16

For the same result you could eliminate v, and bitshift 1 left by i like

for (int i = 0; i <= N; i++) {
    System.out.println(i + " " + (1 << i));
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
1

You added i = i + 1 inside the loop which is not necessary here since its already done by the for loop

You can fix it this way:

public class PowersOfTwo {
    public static void main(String[] args) {
        int N = Integer.parseInt(args[0]); // last power of two to print
        int v = 1; // current power of two
        for (int i = 0; i <= N; i ++) {
            System.out.println(i + " " + v);    
            //i = i + 1; // you dont need this line
            v = 2 * v;
        }
    }
}

Or this way:

public class PowersOfTwo {
    public static void main(String[] args) {
        int N = Integer.parseInt(args[0]); // last power of two to print
        int v = 1; // current power of two
        for (int i = 0; i <= N;) { //no need to i++
            System.out.println(i + " " + v);    
            i = i + 1; 
            v = 2 * v;
        }
    }
}
Ayon Nahiyan
  • 2,140
  • 15
  • 23