Calculate totalPrice in a method/function in Java - java

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.

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).

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;
}

Related

Multiplying user input variables together in another class and then naming that result as a variable

Sorry if this is a bit vague. I am new to learning Java.
In my program I have two classes and one of the classes is for user input. The other class calculates that user input and then returns the calculations to the other class. In my calculations class I'm pretty sure I'm making myself work harder and than I should be. I want to have the result of my user input multiplied together but doing that in the calculations class.
Here is my Calculations class.
class Calculations{
double length, width ;
public double floorArea (double length, double width){
return length * width ;
}
public double floorAreaCost (double length, double width) {
return length * width * 6.50 ;
}
public double serviceCharge (double length, double width){
return length * width / 10 + 12.50 ;
}
}
What I want to be able to do is have return length * width = area. Then use that area variable for future reference in the floorAreaCost method and the service charge method. So instead of return length * width * 6.50 I would have area * 6.50
Here's my user input class as well.
import java.util.Scanner;
public class ApartmentUser{
static Scanner input = new Scanner(System.in);
public static void main (String args[]){
int length, width;
System.out.println("Enter the length of the apartment floor: " );
length = input.nextInt();
System.out.println("Enter the width of the apartment floor: " );
width = input.nextInt();
Calculations area = new Calculations();
System.out.println("The area of the apartment floor is: " + area.floorArea(length, width));
Calculations cost = new Calculations();
System.out.println("The cost of the apartment is: " + cost.floorAreaCost(length, width));
Calculations charge = new Calculations();
System.out.println("The service charge cost is: " + charge.serviceCharge (length, width));
}
}
Your methods should call the floorArea method, so for example method shown below
public double floorAreaCost (double length, double width) {
return length * width * 6.50 ;
}
would become
public double floorAreaCost (double length, double width) {
return this.floorArea(length, width) * 6.50 ;
}
That way, the floor area calculation is encapsulated inside one method only and can easily change in one step
First of all you shouldn't make so many Calculations objects, one is enough.
So what you should do is give the Calculations class a constructor like this.
class Calculations{
public double length, width, area;
public Calculations (int length, int width) {
this.length = length;
this.width = width;
area = width * length;
}
Now when you create youre Calculations object:
Calculations floor = new Calculations(int length, int width);
You directly have the area calculated and you can call the methods without having to input the parameters, because they're already saved in the Calculations class.
You can also work with multiple "rooms", because the informations are saved in the Calculations class.
Hope i could help you.
As written, your Calculations class defines a "stateless" object.
Within each function, the function parameters length and width
hide the member variables length and width,
so that the member variables are never use at all.
You should be able to delete the declaration of those member variables
without noticing any change in the behavior of your program.
This is not necessarily a bad thing. Stateless classes can be very useful.
For example, because Calculations is stateless, you do not need to
allocate three different instances to perform your three different functions.
You can call all the functions on the same instance, because none of the
functions can affect the "state" of the object and therefore cannot have
any hidden "side effects" on the results of functions called later.
The return from each function is determined just by the values you
pass to its two parameters.
The program does end up multiplying the same length and width together
three times when once would have been enough.
You will hardly notice the extra computing time in this example
(it is vastly overshadowed by everything else going on here),
but if you had to do millions of these calculations for one user input
you might then notice a difference.
One way to avoid the redundant multiplications
is to return area from the floorArea function,
but pass area (not length and width) as a single parameter to
each of the other functions.
You might also consider creating member variables of Calculations
to store the numbers 6.5, 10, and 12.5 that you use in some of your functions.
That would allow you to give those numbers meaningful, descriptive names.
It would also permit a more sophisticated version of the program to accept
new values of those constants to use in a Calculations object,
allowing the store to change its pricing without rewriting its software.
If you set those values during the construction of a Calculations object
and do not change them in any of the other functions, the object
is still stateless.
Or you could decide to change the class some other way. I see at least three other answers already, each of which proposes a legitimate design of a Calculations class, no two of those designs the same.
First off all when you define fields in your class, it's common practice to define the scope of the variable. So it would look something like this. Which only makes the variable accessible within the class, if you would access it from the main method, you should declare em public. But add your area as a variable.
private double area ;
You need to store your calculated Area on the object, use the keyword this for accessing that variable. When operations on the same object is done, it can be fetched in a similar fashion.
Update your code to this:
public double floorArea (double length, double width){
this.area = length * width;
return this.area;
}
public double serviceCharge (){
return this.area / 10 + 12.50 ;
}

How do I pass these integers to the method below it?

I'm confusing myself here. My goal was to make a simple program that took the number of values the user wants to average, store them in an array (while adding them together) and finally giving the average of these numbers.
My thing is, I am trying to understand the concept of multiple classes and methods as I am new so I tried using another class just do do all the work, while the Main class would just create the object from the other class, and then run their methods. Maybe I am asking something impossible. Take a look at my code.
This is my Main class:
public class Main
{
public static void main(String[] args)
{
System.out.println("Please enter numbers to average together");
OtherClass averages = new OtherClass();
averages.collectNumbers();
averages.AverageNumbers();
}
}
Now I am not sure if anything goes in those parameters, or if I can even use "averages.AverageNumbers();" without creating another object with "OtherClass" called something else? I am pretty sure it's legal though.
Here is my other class for this project entitled "OtherClass"
import java.util.Scanner;
public class OtherClass // using this to name obj
{
public void collectNumbers() //name of our method that does things
{
Scanner sc = new Scanner(System.in);
System.out.println("how many integers would you like to average? ");
int givenNum = sc.nextInt();
System.out.println("Alright, I will average " + givenNum + " values. \nPress enter after each:");
int[] numCollect = new int[givenNum];
int sum = 0;
for (int i = 0; i < numCollect.length; i++)
{
numCollect[i] = sc.nextInt();
sum = sum + numCollect[i];
}
System.out.println(sum);
}
public int AverageNumbers(int givenNum, int sum)
{
int average = sum / givenNum;
System.out.println(average);
return average;
}
}
So when I run this now with the the method AverageNumbers, it does not work. I am suspecting that maybe I am passing in the integers wrong? I have been toying with it for about an hour now, so I am asking for help. How do I make this work?
This will work if you declare sum and givenNum as fields of your OtherClass, instead of as local variables. So, before the collectNumbers method, write
private int sum;
private int givenNum;
and remove the declarations of these two variables inside collectNumbers. So, for example, instead of
int givenNum = sc.getInt();
you'll just have
givenNum = sc.getInt();
because the variable already exists. Also change the declaration of the averageNumbers method to
public int averageNumbers()
because you no longer need to pass those two values in to this method.
This is the archetypical example of using the objects of a class to carry a small amount of data around, instead of just using a class as a way to group methods together. The two methods of this class work with sum and givenNum, so it makes sense to store these in each object of this class.
Lastly, in your averageNumbers method, you have an integer division, which will automatically round down. You probably want a floating point division instead, so you could write
double average = (double) sum / givenNum;
which converts sum to a double-precision floating point number before the division, and therefore does the division in floating point, instead of just using integers. Of course, if you make this change, you'll need to change the return type of this method to double too.

nothing will print in the compiler. [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Here's the question I was asked:
Write a complete Java program called CalcTotalPrice. The program must include five methods:
getSaleTotal, getSalePrice, getSaleWeight, calcTax, and calcShipping.
getSaleTotal takes no input parameters and returns a double, which is the sale total, and which it computes by calling the other four methods.
getSalePrice returns a double, which it gets from the user at the command line.
getSaleWeight returns a double, which it gets from the user at the command line.
calcTax takes a double as a parameters (the sale price) and returns the tax amount as a double (use 6% as a fixed tax rate).
calcShipping takes a double as a parameter (the sale weight) and returns the shipping amount as a double (calculate shipping as $10 if weight is less than 10 and $20 if weight is 10 or greater).
getSaleTotal should print the sale price amount, tax amount, shipping amount, and sale total amount to the command line.
nothing will print in the compiler. Please help me.
Here's my code:
import java.util.Scanner;
/**
*
* #author Kramer1
*/
public class CalcTotalPrice {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
}
public static double getSaleTotal(){
Scanner in = new Scanner(System.in);
double price = getSalePrice(in);
System.out.println(price);
double tax = calcTax(.06);
System.out.println(tax);
double shipping = calcShipping(in.nextDouble());
System.out.println(shipping);
double saleTotal = ((price)*tax)+price+shipping;
System.out.println(saleTotal);
return saleTotal;
}
public static double getSalePrice(Scanner in){
double salePrice = in.nextDouble();
return salePrice;
}
public static double getSaleWeight(Scanner in){
double saleWeight = in.nextDouble();
return saleWeight;
}
public static double calcTax(double salePrice){
double salesTax = .06;
return salesTax;
}
public static double calcShipping(double saleWeight){
double amountShipping = 0;
if (saleWeight < 10){
amountShipping = 10.;
}else if(saleWeight > 10){
amountShipping = 20.;
}
return amountShipping;
}
}
You arent doing anything in your main()
To see the output, you will have to create the Scanner in main and then call appropriate methods.
You need to do some code refactoring. First, move your Scanner to the main method. Then pass it around as an argument to other methods to read data from or read data in main and pass the values directly. I suggest the latter
You also need to declare the variables you use outside the methods and into the class so that their values persist till the end of the program and you will have access to them in various methods. Do declare them static.
You have a main method that is empty - it is not doing anything or calling any code.
Try instantiating your class and calling some methods in it.
it also looks like it is expecting some input from the user. So also try instantiating a Scanner class in your main which can then be passed to some methods. Remember to also call in.nextLine(); to flush the input before calling the next in.nextDouble();
try
Static Double salesPrice = null;
public static void main(String[] args) {
CalcTotalPrice ctp = new CalcTotalPrice ();
Scanner sc = new Scanner(System.in);
salesPrice = ctp.getSalesPrice (in);
in.nextLine();
//etc
}

Read txt file into array then find min max and average of salaries

Looks like this is the week for this type of question. And after reading through all of the new ones and several old ones, I'm no less confused!
I have a text file with 5 employees, each having 10 salary values listed beneath their name. I am to read in this file, find and display the employee Name, minimum salary, maximum salary and the average salary for each person. I must have 3 loops: One to control reading the file, one to lad the data into the array, and one to do the calculations. I have to print the information for each person on one line, and i must allow decimals rounded to 2 decimal places apparently using Math.round which I've never heard of!
I am embarrassed to show you the mess of code I have because it's not much, but I don't know after reading all that I have if I've even started correctly. I do not know if I have even the right idea of how to proceed. Your help is appreciated.
UPDATED CODE: AGAIN!
import javax.swing.*;
import java.io.*;
public class MinMaxSalary3
{
public static void main(String args[])throws Exception
{
// Declare input file to be opened.
FileReader fr = new FileReader ("salary.dat");
BufferedReader br = new BufferedReader (fr);
//General Declarations
final String TITLE = "Employee's Salary Report";
String employeeName, salaryString;
double avgSalary=0.0;
double totalSalary = 0.0;
double sum = 0.0;
// Declare Named Constant for Array.
final int MAX_SAL = 10;
// Declare array here.
int salary[] = new int[MAX_SAL];
System.out.println (TITLE);
while ((employeeName = br.readLine()) != null)
{
System.out.print ("" + employeeName);
// Use this integer variable as your loop index.
int loopIndex;
// Assign the first element in the array to be the minimum and the maximum.
double minSalary = salary[1];
double maxSalary = salary[1];
// Start out your total with the value of the first element in the array.
sum = salary[1];
// Write a loop here to access array values starting with number[1]
for (loopIndex = 1; loopIndex < MAX_SAL ;loopIndex++)
// Within the loop test for minimum and maximum salaries.
{
if (salary[loopIndex] < minSalary)
{
minSalary = salary[loopIndex];
if (salary[loopIndex] > maxSalary)
maxSalary = salary[loopIndex];
}
{
// Also accumulate a total of all salaries.
sum += sum;
// Calculate the average of the 10 salaries.
avgSalary = sum/MAX_SAL;
}
// I know I need to close the files, and end the while loop and any other loops. I just can't think that far right now.
}
{
// Print the maximum salary, minimum salary, and average salary.
System.out.println ("Max Salary" + maxSalary);
System.out.println ("Min Salary" + minSalary);
System.out.println ("Avg Salary" + avgSalary);
}
System.exit(0);
}
}
}
I must have 3 loops: One to control reading the file, one to lad the
data into the array, and one to do the calculations.
What I've written below might just be more gobbledygook to you now, but if you ever get past this class it might be useful to know.
Another way to look at this would be more object-oriented and better decomposition to boot: You need an object to hold the data, to perform the calculations, and render output. How you get that data is immaterial. It's files today; next time it might be HTTP requests.
Start with an Employee object. I deliberately left out a lot of detail that you'll have to fill in and figure out:
package model;
public class Employee {
private String name;
private double [] salaries;
public Employee(String name, int numSalaries) {
this.name = name;
this.salaries = new double[numSalaries];
}
public double getMinSalary() {
double minSalary = Double.MAX_VALUE;
// you fill this in.
return minSalary;
};
public double getMaxSalary() {
double maxSalary = Double.MIN_VALUE;
// you fill this in.
return maxSalary;
}
public double getAveSalary() {
public aveSalary = 0.0;
if (this.salaries.length > 0) {
// you fill this in.
}
return aveSalary;
}
}
The beauty of this approach is that you can test it separately, without worrying about all the nonsense about file I/O. Get this object right, put it aside, and then tackle the next piece. Eventually you'll have a clean solution when you assemble all these smaller pieces together.
Test it without file I/O using JUnit:
package model;
public class EmployeeTest {
#Test
public void testGetters() {
double [] salaries = { 10000.0, 20000.0, 30000.0, 40000.0 };
Employee testEmployee = new Employee("John Q. Test", salaries);
Assert.assertEquals("John Q. Test", testEmployee.getName());
Assert.assertEquals(10000.0, testEmployee.getMinSalary(), 1.0e-3);
Assert.assertEquals(40000.0, testEmployee.getMaxSalary(), 1.0e-3);
Assert.assertEquals(25000.0, testEmployee.getMinSalary(), 1.0e-3);
}
}
The approach you would want to espouse in this situation is an object-oriented approach. Bear in mind that objects are a representation of related data. Consider that an Employee may have information about their salary, name, and what department they work in (as an example).
But that's just one Employee. You may have hundreds.
Consider creating a model of an Employee. Define what is most pertinent to one of them. For example, they all have to have a name, and have to have a salary.
One would then elect to handle the logic of finding information about the collection of Employees - including min, max, and average salaries - outside of the scope of the generic Employee object.
The idea is this:
An Employee knows everything about itself.
The onus is on the developer to tie multiple Employees together.
It's possible that I don't know enough about what your problem is specifically looking for - I'm not even sure that you can use objects, which would really suck - but this is definitely a start.
As for your compilation errors:
salary is a double[]. An array holds many different values of type double inside of it, but a double[] isn't directly a double. Assigning a non-array type to an array type doesn't work, from both a technical stance, and a semantic stance - you're taking something that can hold many values and trying to assign it to a container that can hold one value.
From your code sample, you want to use a loop (with a loop variable i) to iterate over all elements in salary, and assign them some value. Using just salary[0] only modifies the first element.

Java code what is wrong with this?

I am really new to programming, on netbeans i have deleted all the other text, all i have is the following, Why wont the program run?
The error i get is, no main Class found.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package findcost2;
public class Main
/* a program to calculate and display the cost of a product after
* sales tax has been added*/
public class FindCost2
Public static void main (String[] args)
{
double price,tax;
price = 500;
tax = 17.5;
price = price * (1 + tax/100);// calculate cost
// display results
System.out.println("***Product Price Check");
System.out.println("Cost after tax = " + price);
}
}
Try this exactly and name your java file FindCost2.java
package findcost2;
public class FindCost2{
public static void main (String[] args)
{
double price,tax;
price = 500;
tax = 17.5;
price = price * (1 + tax/100);// calculate cost
// display results
System.out.println("***Product Price Check");
System.out.println("Cost after tax = " + price);
}
}
You're missing a curly bracket after class Main and you have two public classes in the same source file. Delete public class Main and change Public to public.
You should probably also use decimal numbers for dealing with currencies
Sooner or later, everyone trying to calculate money in Java discovers that computers can't add.
Why is Public capitalized? Shoud be:
public class FindCost2 {
public static void main(String[] args) { ... }
}
Numerous problems with this code:
The outer class (Main) does not have an opening bracket. Insert the { bracket.
The inner class (FindCost2) does not have an opening bracket. Insert the { bracket.
The public modifier for the main method is capitalized. Start with a lowercase p.
The main method is nested in an inner class. This is really bad form. To make it work anyway, the inner class needs to be static. Insert the static keyword.
When put like this, it compiles:
public class Main {
/*
* a program to calculate and display the cost of a product after sales tax
* has been added
*/
public static class FindCost2 {
public static void main(String[] args) {
double price, tax;
price = 500;
tax = 17.5;
price = price * (1 + tax / 100);// calculate cost
// display results
System.out.println("***Product Price Check");
System.out.println("Cost after tax = " + price);
}
}
}
However, there is absolutely no point to the outer class (Main). Just delete this. When the outer class is removed, the inner class (FindCost2) need not be static anymore. Remove the keyword.
It is really bad form to declare multiple variables on one line (as in double price, tax;). Split that to two lines:
double price;
double tax;
There are good reasons not to use the double type for monetary values. With a little extra work, you can easily write a simple Money class. Check javapractices.com for a good overview on that.
Hope that helps!

Categories