Search code examples
javachaining

Chaining returns through methods in Java


first off, I'm positive this is a really easy answer, and I apologize.

I'm trying to figure out if I can chain a returned value through methods in the same class, using overloaded methods. In the code below, the computeBill(double bookPrice, int quantity) portion is what I'm currently stuck on.

What I want it to do, is be passed the price of the book, and the quantity. (main has an input section that passes outputs to these methods; that part works fine). It will then pass those to moneyConversion(), which does math, converts to BigDecimal, and returns the result as variable bookPriceDisp. I want computeBill() to return that same value back to main for display.

I'm getting cannot find symbol in class Billing. Do I need to make a new object in each method?

public class Billing
{

public static BigDecimal computeBill(double bookPrice)
{
    BigDecimal bookPriceTaxed = new BigDecimal(bookPriceInput*1.08);
    return bookPriceTaxed;
}

public static BigDecimal computeBill(double bookPrice, int quantity)
{
    moneyConversion(bookPrice, quantity);
    return bookPriceDisp;
}

public static void computeBill(double bookPrice, int quantity, double coupon)
{
    System.out.println("Please enter the percentage of your coupon: ");
    double couponInput = keyboard.nextDouble();
    System.out.println("You entered " + couponInput + "%");
    moneyConversion(bookPrice, quantity);
    BigDecimal couponSavings = new BigDecimal(bookPrice * quantity * couponInput);
    System.out.println("Your books will cost $" + ((bookPriceDisp - couponSavings)*1.08));
    System.out.println("Your coupon saved you $" + couponSavings);

}

public static BigDecimal moneyConversion(double bookPrice, int quantity)
{
 //Using BigDecimal to get correct dollars/cents.
 BigDecimal bookPriceDisp = new BigDecimal(bookPrice * quantity);
 bookPriceDisp = bookPriceDisp.setScale(2, BigDecimal.ROUND_HALF_UP);
 return bookPriceDisp;
}

Thank you,

-Stephan


Solution

  • bookPriceDisp is a local variable of moneyConversion(). A local variable, as its name indicates, is local, and thus not visible/usable outside of the block (i.e. the moneyConversion() method) where it's defined.

    What you want is to return the same value of what the moneyConversion() method returns, so:

    // assign the result of moneyConversion() to a local variable result
    BigDecimal result = moneyConversion(bookPrice, quantity);
    // return this local variable
    return result;
    

    or simply:

    // return the value returned by moneyConversion()
    return moneyConversion(bookPrice, quantity);