简体   繁体   中英

Returning an Double/Integer from a Method in Java?

I am trying to make code that takes a set of numbers in, runs them through the quadratic formula and returns the answer that is then printed.

PS I'm new to java, doing this to learn.

Scanner firstCoeff = new Scanner(System.in);
int ax = firstCoeff.nextInt();
firstCoeff.close();
Scanner secCoeff = new Scanner(System.in);
int bx = secCoeff.nextInt();
secCoeff.close();
Scanner finConstant = new Scanner(System.in);
int c = finConstant.nextInt();

Quadratic_Formula work = new Quadratic_Formula();
work.posquadForm(ax, bx, c);
work.negquadForm(ax, bx, c);

System.out.println("Your answer is" + work.posquadForm() +"or" + work.negquadForm() +".");

Here is the formula class:

public class Quadratic_Formula {
public double posquadForm(int ax, int bx, int c) {
    int b;
    b = (bx);
    int a;
    a = (ax);

    double posanswer;
    posanswer = ((-b) - Math.sqrt((b^2) + ((-4) * a * c)) / (2 * a));
    return posanswer;
}
public double negquadForm(int ax, int bx, int c) {
    int b;
    b = (bx);
    int a;
    a = (ax);

    double neganswer;
    neganswer = ((-b) + Math.sqrt((b^2) + ((-4) * a * c)) / (2 * a));
    return neganswer;
}

Change to

Quadratic_Formula work = new Quadratic_Formula();
double posAnswer = work.posquadForm(ax, bx, c);
double negAnswer = work.negquadForm(ax, bx, c);

System.out.println("Your answer is" +posAnswer  +"or" + negAnswer  +".");

Your functions posquadForm & negquadForm have already computed the answers, you just need to store them in variables and print them out?

Your method is declared as such:

public double posquadForm(int ax, int bx, int c) {

So just pass in those variables...

int valueForAx = 2;
int valueForBx = 3;
int valueForC = 4;
System.out.println("Your answer is " + work.posquadForm(valueForAx, valueForBx, valueForC));

Side note, instead of:

int b;
b = (bx);
int a;
a = (ax);

you just use:

int b = bx;
int a = ax;

And the opposite of Alex K's answer is to not take any parameters, just deal with ax, bx and c as globals (assuming the quad formula class is an inner class).

public double posquadForm() {

    double posanswer;
    posanswer = ((-bx) - Math.sqrt((bx^2) + ((-4) * ax * c)) / (2 * ax));
    return posanswer;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM