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