How could I write an if-then statement that checks if an inputted integer is a perfect square or not (i.e. if I took the square root, it would be an integer as well: 4, 9, 16, 25, 36, etc.) in DrJava? Thank you!
Asked
Active
Viewed 4.0k times
1 Answers
33
I am aware that this question already has an answer.... But just in case, this also works.
int x = (int) Math.sqrt(input);
if(Math.pow(x,2) == input)
//Do stuff

Community
- 1
- 1

Jaskaranbir Singh
- 2,034
- 3
- 17
- 33
-
Would the "int" before x and the "int" in the parentheses be my integer as well? – Brooke Dec 03 '15 at 02:29
-
no. Just replace `yourIntHere`. – Jaskaranbir Singh Dec 03 '15 at 02:30
-
Also, is there a way to negate that? As in saying if "int is _not_ a perfect square." – Brooke Dec 03 '15 at 02:32
-
1just add `else` block after `if` and add your code in that `else` block. – Jaskaranbir Singh Dec 03 '15 at 02:35
-
Awesome! Thank you so much you've been a big help!! :D – Brooke Dec 03 '15 at 02:37