• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

using sqrt()

 
Ian Cockcroft
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am using a little function to return the squre root of an int:
[code]
public double calcSquare(int x)
{
return sqrt(x);

}
[code/]
i get an error,
SquareRoots.java:62: cannot resolve symbol
symbol : method sqrt (int)
location: class SquareRoots
return sqrt(x);
even when i import java.lang.Math;
why?
thanks
Ian
 
Bert Bates
author
Sheriff
Posts: 8898
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ian -
This is tricky because you know you don't need an instance to invoke a static method, so what do you do?
When you use static methods you have to indicate from which class you're getting the method. In this case try:
return Math.sqrt(x); // Math is the class that contains sqrt
The rule to remember is:
"For static methods, use the dot operator on the class name"

There is another tricky shortcut for similar situations: If you have a static member (variable or method) in one of your classes, (say your class is Dog), and you have an instance of that class (Dog d = new Dog(); ), you can also access static members in the class using the shortcut:
d.doStaticMethod(); // using an instance var to access a static method
or
Dog.doStaticMethod();
The first example is really just a compiler trick, but it works.
[ June 04, 2003: Message edited by: Bert Bates ]
 
Ian Cockcroft
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, that works fine, need to study up on static methods, do you know any good books?
 
Bert Bates
author
Sheriff
Posts: 8898
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

hmmm....
 
Michael Morris
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, that works fine, need to study up on static methods, do you know any good books?
This one might help.
 
Ian Cockcroft
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hahaha, Touch´┐Ż.
Thanks for your help guys.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic