How to make calls to methods
New here, I'm a compsci student taking a java programming class. Pretty basic suff but I'm getting caught here and there wrapping my head around some stuff.
My question right now invoves making a method that takes a single int parameter and then prints all of the positive even perfect squares less than n.
This is what I have so far:
Code :
public class evenSquares {
public void evenSquares(int n){
for(int j = 2; j*j <= n; j += 2)
System.out.println(j*j);
}
}
Code :
public class evenSquaresDriver {
public static void main(String[] args){
evenSquares testsquare = new evenSquares(1000);
}
}
This is giving me an error that "The constructor evenSquares(int) is undefined"
Re: How to make calls to methods
Ok, in your evenSquares class, you have no constructor. What you do have is a method. So when you say new evenSquares(1000);, it is looking for a constructor that accepts an int.
So, there are a few ways to fix this with what you already have, depending on what you want to do:
If you want to create a constructor for your evenSquares class:
Code java:
public class evenSquares {
public evenSquares(int n){ //NOTICE: I took out the return type to make it a constructor
for(int j = 2; j*j <= n; j += 2)
System.out.println(j*j);
}
}
OR
If you want to have an evenSquares class, with an evenSquares method (poor programming habit, but it will work):
Code java:
public class evenSquaresDriver {
public static void main(String[] args){
evenSquares testsquare = new evenSquares();
testsquare.evenSquares(1000); //Using the empty constructor, and then calling the evenSquares(int) method
}
}
You seem to not fully understand the difference between a method and a constructor. I suggest you do a little bit of reading about them to better understand how it works.
Re: How to make calls to methods
Another question with similiar idea.
The method stringRoot is passed a string of digits as a paramater and returns the square root of the number represented by those digits.
Code :
public double stringRoot(String str){
double k = Integer.parseInt(str);
return Math.sqrt(k);
}
Code :
stringRoot testDouble = new stringRoot();
testDouble.stringRoot("1600");
It's telling me "stringRoot cannot be resolved to a type"
Correct me if I'm wronge but this is a method correct? I also just threw the codes into my evenSquares and evenSquaresDriver classes
Re: How to make calls to methods
What class is the stringRoot(...) method in?
You are trying to create a new Object, of type stringRoot, and calling the new Object's stringRoot(...) method, which is clearly not what you are wanting to do.
Re: How to make calls to methods
ermmm, just do classname.stringRoot("1600")
don't think you need to make an object to use a classes method?