Jump to content

Powers of ten

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
3 replies to this topic

#1
seph6664

seph6664

    Newbie

  • Members
  • PipPip
  • 10 posts
So I have an assignment where I have to make the program display powers,
1
10
100
1000
etc...
however my program will display a number 12 times (2.147483647E9 << that number). can anyone spot what im doing wrong?


public class PowerGenerator {

public int power;

	


public PowerGenerator(int i) 

{

		power = (int) Math.pow(10,i);

}


public double nextPower() {

	

	return power;

}


}

and my driver is

public class PowerGeneratorRunner {


	public static void main(String[] args)

	{

		PowerGenerator myGenerator = new PowerGenerator(10);

		for (int i = 1; i <= 12; i++)

			System.out.println(myGenerator.nextPower());

		

	}

	}


#2
ZipOnTrousers

ZipOnTrousers

    Learning Programmer

  • Validating
  • PipPipPip
  • 94 posts
Could it be something to do with power being declared public in the PowerGenerator class and the program is getting confused between the local "i" in the for loop and the public "i" in power?

Edited by ZipOnTrousers, 26 October 2009 - 03:03 PM.


#3
Sinipull

Sinipull

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 386 posts
for (int i = 1; i <= 12; i++)
			System.out.println(myGenerator.nextPower());

You are doing this part 12 times, but you are not telling the computer to change the argument after every cycle. You are not using the 'i' ... you are just calling previously calculated power 12 times.

public PowerGenerator(int i) 
{
		power = (int) Math.pow(10,i);
}

This part gets the 'i' only once, when you construct the instance using
 PowerGenerator myGenerator = new PowerGenerator(10);

So all your powers are pow(10, 10)

public double nextPower() {	
	return power;
}
This part doesn't do what it's name says... it just returns the same pow(10, 10) every time you call it.

you should insert the argument from within the "for loop" like this:
for (int i = 1; i <= 12; i++){
	System.out.println(myGenerator.nextPower(i));
}

And now you should edit the nextPower() method, so it'll give you power, based on that 'i'

#4
seph6664

seph6664

    Newbie

  • Members
  • PipPip
  • 10 posts
My program is working perfectly now, thank you for your help.