0

Iam doing a school assignment in Java, and I need some help to do some calculations in a method. Iam used to PHP, and I've appended a lot of my knowledge in the code, but this one I just cant figure out (I know how do do it without the function, but that requires much more lines of code which is stupid).

Here is some of my code:

public static void main (String[] args) { // User inputs calculate("Number of beers", 20, 1.50); } public static void calculate(String articleName, double numberOfX, double pricePerUnit) { double subTotal = numberOfX * pricePerUnit; System.out.printf("%-20s %-1s %10.2f\n", articleName, ":", subTotal); } 

This prints out a nice bill of the things I've bought. Furthermore I would like this method to add the totalprice to a (global?) variable which eventually shows the final price of all items. In PHP i usually wrote a variable named totalDue += subTotal;

Is there any way to do this in java? I would be a shame to write an entire new function to do the math if I just could add the total price of each item into a variable.

2 Answers 2

1

Global variables don't exist in Java.

And this is not how it should be done. Rather than the method updating some variable, the method should just return the result of the computation, and the caller should be responsible of using the result as he wants to:

double total = 0D; total += calculate("Number of beers", 20, 1.50); total += calculate("Number of pizza", 10, 8); // ... 

This way, you won't have to change anything in the calculate method when you'll want to compute subtotals, or averages, or anything. One method = one responsibility.

This should be true for your PHP programs as well.

After this is done, you should encapsulate the article name, number of items, and unit price in a class, and add methods to the class, like toString (to display the bought item), and computePrice (to compute the price of this bought item).

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot! That sure did the trick, and I've learned some good practice too :)
1
public static void main (String[] args) { // User inputs double total = 0.0; total += calculate("Number of beers", 20, 1.50); } public static double calculate(String articleName, double numberOfX, double pricePerUnit) { double subTotal = numberOfX * pricePerUnit; System.out.printf("%-20s %-1s %10.2f\n", articleName, ":", subTotal); return subTotal; } 

1 Comment

Thanks a lot! Since both replies states the same, I'll mark the first one as solution - but thanks a lot to you to!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.