简体   繁体   中英

why won't my code work? new to java

I am very new to the whole CS scene but quickly getting into it, I chose Java as the first language I wanted to learn.

I'm using an online resource that asks me to make a simple program which asks the user to enter a number, and then it spits back out the sum of the powers.

So if you input 4, I want it to give you 2^0 + 2^1 + 2^2 + 2^3 + 2^4 This is what I have so far, but it's not working, any suggestions?

I am using NetBeans.

System.out.println("Type a number: ");
int number = Integer.parseInt(reader.nextLine());
int i = 0;
int exponent = (int)Math.pow(2,i);
int sum = 0;
while (i <= number) {
     sum += exponent;
 i++;
}
System.out.println("The result is: " + sum);

You're assigning a value to exponent outside the loop.

This means that it's value won't change every time i is incremented.

To fix this:

    System.out.println("Type a number: ");
    int number = Integer.parseInt(reader.nextLine());
    int sum = 0;
    for (int i = 0; i <= number; i++) {
        sum += Math.pow(2,i);
    }
    System.out.println("The result is: " + sum);


}

In addition to producing the desired output, this code is more efficient as I've removed the exponent variable (as it can be added straight to sum ), and I've used a for loop (so that there's no need for the line where i is declared or for the line where i is incremented).

Try this:

    int exponent = 0;
    int sum = 0;

    while (i < number) {
        sum += exponent;
        i++;
        exponent = (int) Math.pow(2, i);
    }
    System.out.println("The result is: " + sum);

Whole case with for loop

public static void test(){
    java.util.Scanner reader = new java.util.Scanner(System.in);
    System.out.println("Type a number: ");

    int sum = 0;
    int number = Integer.parseInt(reader.nextLine());

    for (int i = 0; i <= number; i++){
        int exponent = (int) Math.pow(2, i);
        sum = sum + exponent;
    //    System.out.println(i); if you want to see the exponent uncomment this line
    }

    System.out.println("The result is: " + sum);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM