Help with Java assignment
Im in a newb comp sci class and im having trouble with this assignment. It should be easy for you pros so if you guys could help me out on this one.
"Write a program called Power that displays the positive powers of 2. When the user enters the exponent at a prompt, the program displays 2 to that power. The program halts when the user enters -1. (You may not use the Math.pow() method, must use a for loop)"
I dont necessarly need you to write the whole thing for me im not exactly sure wat im supposed to do to make it loop.
[547 byte] By [
MindGAckt] at [2007-11-11 9:40:45]

# 1 Re: Help with Java assignment
ok, well do you know what a power is? for example if you have 2^2 (2 sqaured) it is 2*2.
2^10 = 2*2*2*2*2*2*2*2*2*2
2^9 = 2*2*2*2*2*2*2*2*2
and so on
so now that you should understand what a power is, you should use a for loop to do the calculations. something like this:
// power is the user specified number
for(int i = 1; i < power; i++)
{
// do the calculations in here
}
anubis at 2007-11-11 22:32:38 >

# 2 Re: Help with Java assignment
Yea that helped thx a lot.
edit: crap i need help again. I cant figure out the part where the program ends when the user inputs -1. This is wat i have so far import java.util.Scanner;
public class Power {
public static void main(String[] args) {
int num1 = 2;
int power;
boolean quit = false;
double result = 0;
Scanner reader = new Scanner(System.in);
while(!quit){
System.out.println("Enter the power: ");
power = reader.nextInt();
for(int i = 1; i < power; i++){
result = Math.pow(num1,power);
}
if(power = -1){
quit = true;
}
}
System.out.println("" +result);
}
}
I prolly just messed up the whole thing but what "if" doesnt work. So wat should i put instead?
# 3 Re: Help with Java assignment
for(int i = 1; i < power; i++){
result = Math.pow(num1,power);
i thought you couldnt use Math.pow?
and for your if statement, change it to this:
if(power == -1)
quit = true;
anubis at 2007-11-11 22:34:42 >

# 4 Re: Help with Java assignment
Yea i changed it, but now im not sure how to make it so num1 is to the power of "power".
import java.util.Scanner;
public class Power {
public static void main(String[] args) {
int num1 = 2;
int power;
boolean quit = false;
int result = 0;
Scanner reader = new Scanner(System.in);
while(!quit){
System.out.println("Enter the power: ");
power = reader.nextInt();
if(power == -1){
quit = true;
}
else if(power != -1){
for(int i = 1; i < power; i++){
result = power*(num1*power);
}
System.out.println("Answer: " +result);
}
}
}
}
# 5 Re: Help with Java assignment
Think of it this way, if you do what you are programming you would have what if you did 5 to the power of 8 ...
Answer = 8*(5*8)
You want an Answer of (((((((5*5)*5)*5)*5)*5)*5)*5)
To get that try;
result = result * num1
# 6 Re: Help with Java assignment
Yea result = result * num1 worked.
Thx for the help, and btw ignore wat i put for result before :P