Search code examples
javamain-method

How to call a method from main, even though I haven't defined variables in main.


I haven't initialized anything on main. All I want is to call an outside method. However, when calling on picnicCost(), I don't know what to put inside the parenthesis since I didn't use any variables in main.

import java.util.*;
public class picnic
{
static Scanner scan=new Scanner(System.in);
public static void main(String args[])
{
picnicCost(0,0,0);  
}

public static double flatFee(double a)
{
    System.out.println("Enter the number of people attending: ");
    a=scan.nextDouble();
    return a*5.00;
}

public static double MealP(double b)
{
    System.out.println("Enter the number of poeple purchasing a meal: ");
    b=scan.nextDouble();
    return b*2.75;  
}

public static double iceCreamCost(double c)
{
    System.out.println("Enter the number of poeple purchasing ice cream: ");
    c=scan.nextDouble();
    return c*.75;   
}


 public static double picnicCost(double a, double b, double c)
 {
     return flatFee(a) + MealP(b) + iceCreamCost(c);     
 }

 }

Solution

  • You should only pass something as an argument if you need prior information to do what you want to do, so the parameters of flatfee and co. should be empty:

    flatFee() { // code here }
    

    you then declare a as a local variable:

    flatFee() {
        double a;
        // do stuff
        return a * 5.0;
    }
    

    After that, you can pass the result of methods as arguments directly without using variables like so:

     picnicCost(flatFee(), MealP(), iceCreamCost());