Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Do I Use A Function in Main?

I'm stuck in my program. I need help using a function in the main method. So far I have this:

    double x, y;
    char op;

    System.out.print("X: ");
    x = keyboard.nextDouble();
    System.out.print("Y: ");
    y = keyboard.nextDouble();

    System.out.print("Enter Operation: ");
    op = keyboard.next().charAt(0);

    do
    {   
        if (op == '+');
            System.out.print("..");

    }
    while (op != 'q');

    System.out.print("Bye!");
}

public static double sum (double x, double y)
{
    double sum = 0;
    sum = (x + y);

    return sum;
}
public static double minus (double x, double y)
{
    double minus = 0;
    minus = (x - y);

    return minus;
}
public static double multiply (double x, double y)
{
    double multiply = 0;
    multiply = (x * y);

    return multiply;
}
public static double divide (double x, double y)
{
    double divide = 0;
    divide = (x/y);

    return divide;
}

For the "if statement" I want to use the functions. If the operation is '+' then it would use the sum function to add x and y. But how do I type it in the "if statement"? Sorry. It's my second programming class so I'm still learning.

like image 841
Marcella Ruiz Avatar asked Jul 23 '26 09:07

Marcella Ruiz


1 Answers

You call another function something like this:

double output = sum(1,3);

Even more generally, it goes something like this:

OutputType VariableToHoldOutput = MethodName(Parameter1, Parameter2, etc);

With the output being optional to store. If the output type is void, you cannot even store it. That would result in something like this

MethodName(Parameter1, Parameter2, etc);

ALSO, an if statement is not followed by a semicolon. The way you have it is equivalent to:

if (op == '+')
{
    ;
}
System.out.print("..")

You probably want something more like:

if(op == '+')
{
    double output = sum(X,Y);
    System.out.print("Output = " + output);
}
like image 124
Justin Pihony Avatar answered Jul 26 '26 11:07

Justin Pihony



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!