powers of 2 java code help with my input different outcome -
import java.util.scanner; public class powersof2 { public static void main(string[] args) { int inputpowersof2; int powerof2 = 1; int exponent; int exponent2; scanner scan = new scanner(system.in); system.out.println("how many powers of 2 printed?"); inputpowersof2 = scan.nextint(); system.out.println("\n\n"); if(inputpowersof2 >= 2) { system.out.println("here first " + inputpowersof2 + " powers of 2:"); system.out.println(); } else { system.out.println("here first power of 2:"); system.out.println(); } exponent2 = 0; exponent = 0; while(exponent <= inputpowersof2) { system.out.print("2^" + exponent2 + " = "); exponent2++; system.out.println((powerof2 = 2 * powerof2) / 2); exponent++; } } }
why when give me 1 power of 2 prints
2^0 2^1
and when give me 2 powers of 2 prints
2^0 2^1 2^2
and on...
replace
while(exponent <= inputpowersof2)
with
while(exponent < inputpowersof2)
as others said in comments, very, easy solve using debugger.
hope helps,
Comments
Post a Comment