Reputation: 47
This code takes two numbers a base, and an integer, and it multiplies it out, but when I try and run it, it takes the numbers, then nothing happens.
import java.util.Scanner;
public class RaisedToThePower
{
public static void main(String [] args)
{
Scanner reader = new Scanner(System.in);
int base;
int exponent;
double x;
System.out.println("Enter the base");
base = reader.nextInt();
System.out.println("Enter the exponent");
exponent = reader.nextInt();
x = base^exponent;
while (exponent > (-1));
{
System.out.println(x);
}
while (exponent <= -1);
{
System.out.println("Thanks for playing");
}
}
}
Upvotes: 0
Views: 1046
Reputation: 1
That is not how you get power of a base:
x = base ^ exponential;
A simple Math.pow example, display 2 to the power of 8.
Math.pow(2, 8)
First answer already explains everything.
Upvotes: -2
Reputation: 95
You have ; at end of each while loop while (exponent > (-1)); And you are not doing anything inside the both loop except printing. Any of the loop get hit it will be infinite loop.
Upvotes: 0
Reputation: 2415
Why nothing prints:
You are not printing anything, since you do
while (exponent > (-1)) ;
The ;
ends the while statement and since it is an infinite loop you never print anything.
{
System.out.println(x);
}
This is just a statement in a block, which does not belong to the while
To fix this:
while (exponent > (-1)) // no ; here
{
System.out.println(x);
}
This will still be an endless loop, if the exponent is bigger than -1.
The next while has the same problem.
Additional problem:
x = base^exponent;
This does not execute an exponentiation.
^
is the XOR operator in java. (See Java Operators)
To get the power of an exponent you need to use:
Math.pow(base, exponent);
From the java docs:
Returns the value of the first argument raised to the power of the second argument.
Upvotes: 5