Calling a method with parameters within another method located in a superclass - java

I was wondering how I could call getJD() within getToD and keep the parameters intact,(or temporarily set the parameters as variables in main and call the variables to the method).
The parameters are going to be input using the scanner class later in the main method.
import static java.lang.Math.*;
public class jdMethods
{
public static double getJD(double y, double m, double d){
if (m<=2.0){
y--;
m += 12.0;
}
double a=floor(y/100.0);
return (365.25*(y+4716.0))+(30.6001*(m+1))+d+(2.0-a+floor(a/4.0))-1524.5;
}
public static double getToD(int h, int m, int s)
{
double a = getJD(a, a, a) + ((h-12)/24) + (m/1440) + (s/86400);
return a;
}
}
Edited for clarity.

It's not perfectly clear on what you are trying to do, but I assumed that you just want to save the result of your first getJD() and to use the result within your getToD(), so I made a private _jd and created a setter and getter for it.
import static java.lang.Math.*;
public class jdMethods
{
private double _jd;
public double getJD(){
return _jd;
}
public void setJD(double y, double m, double d){
if (m<=2.0){
y--;
m += 12.0;
}
double a=floor(y/100.0);
_jd = (365.25*(y+4716.0))+(30.6001*(m+1))+d+(2.0-a+floor(a/4.0))-1524.5;
}
public double getToD(int h, int m, int s)
{
double a = getJD() + ((h-12)/24) + (m/1440) + (s/86400);
return a;
}
}
So here is how you call it:
jdMethods testRun = new jdMethods();
testRun.setJD(1,2,3);
System.out.println(testRun.getToD(3, 2, 1));

All those parameters will be intact since you are using double and int, those are not Object s so it's value is copied when passed to a function, unlike Object s that a reference to it is passed to the function.
About your code, undefined variable a won't let it compile:
double a = getJD( a, a, a ) + ((h-12)/24) + (m/1440) + (s/86400);
I don't get what you are trying to do there, remember that a from getJD method is not the same a into getToD.

Related

Java multiple interface with parameter

Suppose i have 2 interface which is
interface add{
void add2No(float a, float b);
}
and
interface Minus{
void Minus2No(float a, float b);
}
then on the main method, i already overide the method which is
public class Count implements Add, Minus {
public static void main(String[] args) throws IOException{
//declare var
float a, b;
String temp;
//create object
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Count obj = new Count();
//User Input
System.out.print("Enter your first Number : ");
temp = br.readLine();
a = Float.parseFloat(temp);
System.out.print("Enter your second Number : ");
temp = br.readLine();
b = Float.parseFloat(temp);
System.out.println("Value of " +a+ " + " +b+ " is : " +obj.Totaladd(float a, float b));
System.out.println("Value of " +a+ " + " +b+ " is : " +obj.TotalMinus(float a, float b));
}
#Override
public void Add2No(float a, float b) {
float TotalAdd = a + b;
}
#Override
public void Minus2No(float a, float b) {
float TotalMinus = a - b;
}
}
Am i using the correct implementation for interface? why there's error when i try to print out the TotalAdd and TotalMinus?
Yes. Because you don't return the results. Currently both methods are void. You could change that. Like,
interface Add {
float add2No(float a, float b);
}
interface Minus {
float minus2No(float a, float b);
}
And then
#Override
public float add2No(float a, float b) {
return a + b;
}
#Override
public float minus2No(float a, float b) {
return a - b;
}
There are three wrong places.
The first wrong place:
Because Java is case sensitive.
The name of your interface method is called add2No, but the name of
your implementation is called Add2No
The second wrong place:
There is a problem with your method parameter passing and the way of
calling. I did not see the Totaladd and Totaladd methods defined in
your Count object.
If you adjust the case, there should only be add2No and Minus2No
methods in Count object.
You need to adjust the name of one of them, and do not pass the type when passing parameters.
For example: obj.Totaladd(float a, float b) should be obj.Totaladd(a, b)
The third wrong place:
If you need to call the method to get the value for calculation, you must adjust the type of the method, it should not be void

Difference between Static and Non-Static methods/Subroutines

I was reading a java book, where I came across this statement:
So, every subroutine is contained either in a class or in an object
I'm really confused why does it say "class or in an object"
I would like some explanation.
Let's try this example
public class Demo {
public static void classMethod() {
System.out.println("Call to static method");
}
public void objectMethod() {
System.out.println("Call to object method");
}
public static void main(String[] args) {
Demo demo = null;
demo.classMethod();
//demo.objectMethod();// throws NPE if uncommented
}
}
This code will work (even if the demo variable is null) because static method classMethod is contained within the class Demo. The commented line will throw a NullPointerException because the method objectMethod is not contained in the class but in the object so will need an instance of Demo class to call it.
Subroutine is a method written inside a class. We use them to do various tasks. That statement states that these methods/subroutines are written in an object or a class.
If we have an object instantiated, it will create new methods for every non-static method for that object which were defined in the class of the object. Hence those non-static methods/subroutines are in the object.
But if the class is a static class, we can't have any objects from it. But we can use subroutines/methods of that class. So, they are in a Class
That's what your statement says.
EDIT:
I thought to give an example for this.
public class ExampleClass {
public String getNonStaticString() {
return "This String is From Non-Static Method";
}
public static String getStaticString() {
return "This String is From Static Method"
}
}
Then, if you need to get the static String, all you have to do is
String staticString = ExampleClass.getStaticString();
Note that I havn't created an object from the ExampleClass Here. I just used the method.
But, if you need to get the String from the non-static method, you should instantiate an object first.
ExampleClass exampleObject = new ExampleClass();
String nonStaticString = exampleObject.getNonStaticString();
static methods also known as class method. Static method associated only with the class and not with any specific instance of that class(object).
So, every subroutine is contained either in a class or in an object
The statement is technically not 100% correct.
First of all, subroutines in java are commonly called methods. The following two terms are often used interchangeably:
Method: A subroutine working with an object instance, this.
Function: A subroutine not working with an object instance.
Here is an example scenario which should you get an idea what that means:
public class Circle {
//region static code
//we cannot call "this" in a static context, main(String[]) is no exception here
public static void main(String[] args) {
Circle a = new Circle(0, 0, 10);
Circle b = new Circle(10, 10, 2);
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("circumference of a = " + a.getCircumference());
System.out.println("circumference of b = " + b.getCircumference());
System.out.println("area of a = " + a.getArea());
System.out.println("area of b = " + b.getArea());
System.out.println("distance of a, b = " + distance(a, b));
System.out.println("a, b intersect = " + (intersects(a, b) ? "yes" : "no"));
}
//we cannot call "this" in a static context, but we have the circles a, b as parameters we can use to calculate their distance
public static double distance(Circle a, Circle b) {
return Math.sqrt(squared(a.x - b.x) + squared(a.y - b.y));
}
//we cannot call "this" in a static context, but we have the circles a, b as parameters we can use to check for an intersection
public static boolean intersects(Circle a, Circle b) {
return a.radius + b.radius > distance(a, b);
}
//we cannot call "this" in a static context, but we have the number x as parameter we can use to calculate the square of
public static double squared(double x) {
return x * x;
}
//we cannot call "this" in a static context, but we have the number radius as parameter we can use to check if its value is in range
public static void checkRadius(double radius) {
if(radius < 0) {
throw new IllegalArgumentException("radius must be >= 0");
}
}
//endregion
//region member / instance code
private double x;
private double y;
private double radius;
public Circle(double x, double y, double radius) {
checkRadius(radius);
this.x = x;
this.y = y;
this.radius = radius;
}
//region getters and setters
//we may refer to the instance variables with or without "this", sometimes it is necessary to clarify - see: setX(double)
public double getX() {
return x;
}
//we may refer to the instance variables with or without "this", but in this case we have two variables with name "x"
//if we write "x", the parameter is taken. for the circle's x coordinate, we need to clarify with "this.x"
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
checkRadius(radius);
this.radius = radius;
}
//endregion
//we may refer to the instance variables with or without "this", sometimes it is necessary to clarify - see: setX(double)
public double getCircumference() {
return 2 * Math.PI * radius;
}
public double getArea() {
return Math.PI * squared(radius);
}
//we may refer to the instance variables with or without "this", sometimes it is necessary to clarify - see: setX(double)
#Override
public String toString() {
return "circle at [" + x + ", " + y + "] with radius " + radius;
}
//endregion
}
Output:
a = circle at [0.0, 0.0] with radius 10.0
b = circle at [10.0, 10.0] with radius 2.0
circumference of a = 62.83185307179586
circumference of b = 12.566370614359172
area of a = 314.1592653589793
area of b = 12.566370614359172
distance of a, b = 14.142135623730951
a, b intersect = no

Why won't variabes from other methods return to the main method? (more inside)

The purpose of this program is to print
the number of solutions and the solution(s) to a quadratic function,
entered by the user.
The problems here is that I get errors for having private variables,
why is this? Also for my constructor it states that my variables cannot be resolved even though
they are established in the main method. Finally, my variables will pass to the main method or to the "toString" method for use
in the main method.
This is for a school assignment and my professor requires that I use the "toString" method as well as have private variables. I apologize in advance for any formatting mistakes and for the large question, for I am new
to this site.
import java.util.Scanner
public class QuadraticSolver
{
private static Scanner in;
public static void main(String[]args)
{
QuadraticSolver qs = new QuadraticSolver();
in = new Scanner(System.in);
private double a;
private double b;
private double c;
System.out.println("Enter coefficients for quadratic function. ");
a = in.nextDouble();
b = in.nextDouble();
c = in.nextDouble();
qs.getRoot1(a,b,c);
qs.getRoot2(a,b,c);
qs.numOfSolutions(a,b,c);
System.out.println("Your quadratic function is " + a + "x^2 + " + b + "x + " + c);
System.out.println(qs.toString());
}
public QuadraticSolver()
{
a = 0;
b = 0;
c = 0;
}
public double getRoot1(double a,double b,double c)
{
private double root1;
root1 = (-b + Math.sqrt(Math.pow(b,2) - 4*a*c)) / (2*a);
return root1;
}
public double getRoot2(double a,double b,double c)
{
private double root2;
root2 = (-b + Math.sqrt(Math.pow(b,2) - 4*a*c)) / (2*a);
return root2;
}
public int numOfSolutions(double a,double b,double c)
{
private int sol = 0;
private double d;
d = Math.pow(b,2) - 4*a*c;
if(d > 0)
{
sol = 2;
}
else if(d == 0)
{
sol = 1;
}
else if(d < 0)
{
sol = 0;
}
return sol;
}
public String toString()
{
return "There are(is) " + sol + " solution(s). x = " + root1 + " x = " + root2;
}
}
You should move the variables to the class level:
public class QuadraticSolver {
private double a;
private double b;
private double c;
...
}
Next, you need to access the variables that belong to the object qs:
public static void main(String[]args)
{
QuadraticSolver qs = new QuadraticSolver();
in = new Scanner(System.in);
System.out.println("Enter coefficients for quadratic function. ");
qs.a = in.nextDouble();
qs.b = in.nextDouble();
qs.c = in.nextDouble();
...
}
And finally, you should remove the variables from the methods getRoot1(), etc. This is because each method can access the variables a,b,c belonging to the object itself. Thus:
public double getRoot1()
{
double root1 = (-b + Math.sqrt(Math.pow(b,2) - 4*a*c)) / (2*a);
return root1;
}
And at the call sites:
public static void main(String[]args)
{
...
double root1 = qs.getRoot1();
double root2 = qs.getRoot2();
int numsol = qs.numOfSolutions();
...
}
Private instance variables belong to a class. When you create an object that is an instance of a class, the object may have instance variables that belong to the object; if you create multiple instances of a class, each of those instances (objects) has its own set of instance variables. You declare those in the class:
public class QuadraticSolver
{
private static Scanner in;
private double a; // instance variables
private double b;
private double c;
Now, to access those variables, you need to have an object. If you're in a non-static method inside the class, or in a constructor for the class, the method will work with an object called this, so you could say this.a or just a to get at that variable. If you're outside the class, or in a static method in the class (including main), you need to tell it what object you're working with. In your program, your main method has an object qs that is a QuadraticSolver, and you can get at that object's instance variables by saying qs.a, qs.b, etc.
Variables declared inside a method are local variables. They're for use only within that method. They don't declare instance variables for an object. You can't use the keyword private on them, because that keyword is only for instance variables (and other things that aren't variables). You can't use the variables outside that method. If you declare them in an inner set of curly braces, you can't use them outside the curly braces. If you declare a local variable that's the same name as an instance variable, there's no connection between the two.

Why wont my code run? Java program to add numbers

Can you help me find my error?
I'm trying to use these two methods here but my output is not working.
class Nine {
public static void Nine(String[] args) {
int x,y,z;
y = 3;
x = 7;
z = addEm(a, b);
System.out.println("answer= " +x);
}
public static addEm (double a, double b){
int c;
c = a+b;
}
}
Actually there are a lot of error in your code:
z=addEm(a, b);
here a and b are meaningless, you should use z=addEm(y,x); (if your intent is to sum three with seven)
System.out.println("answer= " +x);
I guess that you want to show the the results of the sum, therefore you should print z (and not x), so you should substitute with System.out.println("answer= " +z);
public static addEm (double a, double b) {
Here you missed the return type, and you need to consider also the type of parameters a and b. Since y,x and z are int, it is better if also a and b are int, and therefore specify also the return type as int:
public static int addEm (int a, int b) {
Or you can declare everything (y,x,z,a,b and return type) as a double: the important here is that they should be all of the same type. Moreover you miss also the return statement of the function addEm, that summarizing becomes:
public static int addEm (int a, int b)
{
int c;
c=a+b;
return c;
}
And finally also the function
public static void Nine(String[] args)
it is not right named for an entry point: its names should be main.
So in conclusion, if you apply all the fix (by modifying as less as possible your original code) a code that compile, run and works following some 'logic' is:
class Nine {
public static void main(String[] args) {
int x, y, z;
y = 3;
x = 7;
z = addEm(y, x);
System.out.println("answer= " + z);
}
public static int addEm(int a, int b) {
int c;
c = a + b;
return (c);
}
}
Man, this is a very basic java lesson:
every prog need an entry point, which is in java:
public static void main(String args[]){}
And then your code will execute.
You're passing arguments a and b to addEm, but those variables aren't initialized. I'm expecting you wanted to pass x and y instead.
class Nine
{
public static void Nine(String[] args)
{
int x,y,z;
y=3;
x=7;
z=addEm(x, y);
System.out.println("answer= " +x);
}
public static addEm (double a, double b)
{
int c;
c=a+b;
}
}
Your code will not work because your addEm method does not have any return type. In addition, the method you wrote takes Double params but while using you are trying to pass int to it. You also do not have any main method. I am assuming you misspelled or misunderstood the main method so below is the code which should work
class Nine
{
public static void Main(String[] args)
{
int x,y,z;
y=3;
x=7;
z=addEm(x, y);
System.out.println("answer= " + x);
}
public static int addEm (int a, int b)
{
int c;
c=a+b;
return c;
}
}

Java - function as parameter

I read the next answer about passing function as parameter.
Still, I don't get the idea. My function can get any function: sin(x), cos(x), etc.
As I understood, I can create an interface, for example:
public interface functionI<T> {
}
that would wrap It.
Now I have my function:
public void needToDo(functionI<Integer> a, int x0Par, int hPar){
}
(needToDo, for example, need to substitue the x of the function n x0par and hPar, and find the Max. If I got sin(x), I need to find the max of sin(x0Par) and (sin(hPar)).
I didn't understand how I use it in my function. How will I know what to do when I got the function, that can be anything (polynomial, sin(x), and so on)
Something like this:
public interface Function1<RESULT,INPUT> {
RESULT call(INPUT input);
}
public class Sin implements Function1<Double,Double> {
public static final Sin instance = new Sin();
private Sin() {
}
public Double call(Double x) {
return Math.sin(x);
}
}
public Double needToDo(Function1<Double,Double> aFunction, Double x0Par, Double hPar) {
Double d1 = aFunction.call(x0Par);
Double d2 = aFunction.call(hPar);
return d1 > d2 ? d1 : d2;
}
public static void main(String[] args) {
Double x0Par = 10.2;
Double hPar = 1.9;
Double ret = needToDo(Sin.instance, x0Par, hPar);
System.out.println(ret);
}
It doesn't quite work like that; you cannot pass arbitrary functions as parameters in Java, instead you pass objects which have specific, often generic sounding, functions.
So you could define a MathOperation interface, which has an execute method, taking a double and returning a double.
public interface MathOperation {
double execute(double x);
}
and then you can create
public class Sin implements MathOperation {
public double execute(double x) { return Math.sin(x); }
}
and have a function that uses it like
public void needToDo(MathOperation op, double x) {
System.out.println(op.execute(x));
}
You could create an on-the-fly function for needToDo like
...
needToDo(new MathOperation() {
public double execute(double x) { return x * 2.0; }
});
...
But you can't pass Math.sin as a parameter. There are reflection tricks you can do, but that's another issue.

Categories

Resources