0

I'm trying to make a number squared (for example, x^2) in Android code, but I get this error:

The operator ^ is undefined for the argument type(s) int, boolean

is there a different way to square a number/variable in Android?

Cœur
  • 37,241
  • 25
  • 195
  • 267
David Elliott
  • 113
  • 1
  • 3
  • 10

3 Answers3

8

do same as you do it in core java,use. Math.pow(yournumber,power) works like yournumber^power.

import java.lang.*;

public class MathDemo {

   public static void main(String[] args) {

  // get two double numbers
  double x = 2.0;
  double y = 5.4;

  // print x raised by y and then y raised by x
  System.out.println("Math.pow(" + x + "," + y + ")=" + Math.pow(x, y));// works like x^y
  System.out.println("Math.pow(" + y + "," + x + ")=" + Math.pow(y, x));//works like y^x

   }
}
nobalG
  • 4,544
  • 3
  • 34
  • 72
3

You can use java's Math.pow() in android too

double power = Math.pow(2,2);
Biraj Zalavadia
  • 28,348
  • 10
  • 61
  • 77
  • No offence, but will you please edit this and rephrase it like,"You can use java's math.pow() in android too".it seems like you are taking credits away from java... :p – nobalG Aug 03 '14 at 14:07
1

If you just need an integer squared, you can do x*x.

Careful, as it might overflow.

Another option is java.lang.Math#pow, but that works on floating point numbers.

Thilo
  • 257,207
  • 101
  • 511
  • 656