issac
issac

Reputation: 13

displaying list of powers program

I really need help with creating a program that displays a list of powers

here is the input and the output:

Input to the application is to include numbers to represent the following:

base exponent (between 1 and 10)

Output is to list the number that you entered as a base and find the powers for that base from 1 up to the ending exponent number that is input.

I'm almost done the program, but the problem is that the program only calculate the base to the power without listing a list of powers.

I know i'm missing something in my loop here is my code

double baseIn, exponentIn;

baseIn = Integer.parseInt(txtBase.getText());
exponentIn = Integer.parseInt(txtExponent.getText());
 //  power = (int) Math.pow(baseIn, exponentIn);

for (int i = 1; i <= exponentIn; i++) {
    txtArea.setText(Integer.toString((int) baseIn)+ "to the power of " + i + "=" + Math.pow(baseIn, i) );

}

Upvotes: 1

Views: 950

Answers (2)

Lutz Lehmann
Lutz Lehmann

Reputation: 26040

One problem could be that you overwrite the test string of the output text area in each iteration of the loop, so that at the end -- probably without seeing anything else, because your code happens so fast that no repaint occured -- you, only see the last output.

Use a stringbuilder, append the string of each iteration, and only display the combined result after the loop.

Or use the already existing functionality

textArea.append(text + newline);

see for instance Java Swing: Approach for dynamically appending text in text area, have scrollbar update

Upvotes: 0

StreamingBits
StreamingBits

Reputation: 137

The following is a recursive solution. Explained in steps. Assuming you want 2^4

1) we call power(2,4)

2) power(2,4) calls power(2,3)

3) power(2,3) calls power(2,2)

4) power(2,2) calls power(2,1)

5) power(2,1) calls power(2,0)

6) power(2,0) returns 1

7) power(2,1) returns (2 * 1) or 2

8) power(2,2) returns (2 * 2) or 4

9) power(2,3) returns (2 * 4) or 8

10) power(2,4) returns (2 * 8) or 16

public static int power(int base, int power){

     if (power == 0)

          return 1;

     else

          return base * power(base, power-1);

}

Upvotes: 1

Related Questions