I have
System.out.printf("$%.2f\t $%.2f\n ",c.getDifference(),c.getAccValue());
but c.getAccValue() always gives me the wrong output and I have no idea why. The formula for getDifference() is getAccValue() - principal, and that output is correct.
I used input 5000 8.25 5 quarterly
CD class:
package cd;
public class CD {
private int time; //in years, t
private double interest; //interest rate, r
private int principal; //principal, p
private String number;//number of times compounded, n
public CD(int time, double interest, int principal, String number){
this.time = time;
this.interest = interest;
this.principal = principal;
this.number = number;
}
public int getTime(){
return time;
}
public double getInterest(){
return interest;
}
public int getPrincipal(){
return principal;
}
public String getNumber(){
return number;
}
public double getAccValue(){
double A = 0;
interest = interest/100;
if( "daily".equals(number)) {
A = Math.pow(1 + interest/365, 365*time) * principal;
}
else if ("weekly".equals(number)){
A = Math.pow(1 + interest/52, 52*time) * principal;
}
else if ("monthly".equals(number)){
A = Math.pow(1 + interest/12, 12*time) * principal;
}
else if ("quarterly".equals(number)){
A = Math.pow(1 + interest/3, 3*time) * principal;
}
else if ("semiannually".equals(number)){
A = Math.pow(1 + interest/2, 2*time) * principal;
}
else if ("annually".equals(number)){
A = Math.pow(1 + interest/1, 1*time) * principal;
}
return A;
}
public double getDifference(){
return getAccValue() - principal;
}
}
CDTest class:
package cd;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class CDTest {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
String input = JOptionPane.showInputDialog("Enter Principal value, "
+ "Interest rate, time (in years), " + " and number of months"
+ " compunded" + "\n(Separated by spaces)");
Scanner in = new Scanner(input);
int principal = in.nextInt();
double interest = in.nextDouble();
int time = in.nextInt();
String number = in.next();
CD c = new CD(time, interest, principal, number);
System.out.println("Principal " + "Interest " + "Maturity " +
"Number Compounded " + "Amount Gained " +
"Accumulated Value " + "");
System.out.println("========= " + "======== " + "======== "
+ "================= " + "============= " +
"================= ");
System.out.printf(" $" + c.getPrincipal() + "\t ");
System.out.print(c.getInterest() + "%" + "\t ");
System.out.print(c.getTime() + "\t ");
System.out.print(c.getNumber() +" \t");
System.out.printf("$%.2f\t $%.2f\n ",c.getDifference(),c.getAccValue());
}
}
Thanks for the help in advance
Edit:
Current output is:
Principal Interest Maturity Number Compounded Amount Gained
========= ======== ======== ================= =============
$5000 8.25% 5 quarterly $2510.99
Accumulated Value
=================
$5020.66
Expected output is:
Principal Interest Maturity Number Compounded Amount Gained
========= ======== ======== ================= =============
$5000 8.25% 5 quarterly $2510.99
Accumulated Value
=================
$7510.99
else if ("quarterly".equals(number)){
A = Math.pow(1 + interest/3, 3*time) * principal;
You're multiplying by 3. But there are 4 quarters in a year. So, I would double check this formula.
Also, you have this line:
interest = interest/100;
in getAccValue. This permanently changes the interest rate. But, getAccValue is called by getDifference. So when the difference is calculated, it divides the interest rate by 100 - and then when getAccValue is called by itself, it divides the interest rate by 100 again. So now your interest rate is tiny and it's showing hardly any money made at all.
Related
I am writing a few java classes for a uni assignment and am having some trouble understanding what is going behind the scenes when I am trying to round to 2 decimal places. I have searched around but can't seem to find an answer that solves this particular version of the problem. So my code asks users to input prices into a cash register program and then prints the total price as well as the number of items. The total price has to be stored as an integer value (i.e 3.21 would be 321) but then outputted as a decimal value at the end. Here's my code:
public class CashRegister_Re_Implementation {
private double totalPrice;
private int itemCount;
CashRegister_Re_Implementation() {
totalPrice = 0;
itemCount = 0;
}
public double getTotal() {
String roundOff = String.format("%.2f", ((totalPrice * 100) / 10000));
double newDecimal;
newDecimal = Double.parseDouble(roundOff);
return newDecimal;
}
public int getItemCount() {
return itemCount;
}
public void addItem(double price) {
totalPrice += price * 100;
itemCount++;
}
}
class CashRegisterTest {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
CashRegister_Re_Implementation reg1 = new CashRegister_Re_Implementation();
int count1 = 0;
System.out.println("Register 1 (2 items)");
while (count1 < 2) {
System.out.print("Item price: £");
double price = scan.nextDouble();
reg1.addItem(price);
count1++;
}
CashRegister_Re_Implementation reg2 = new CashRegister_Re_Implementation();
int count2 = 0;
System.out.println("\nRegister 2 (2 items)");
while (count2 < 2) {
System.out.print("Item price: £");
double price = scan.nextDouble();
reg2.addItem(price);
count2++;
}
CashRegister_Re_Implementation reg3 = new CashRegister_Re_Implementation();
int count3 = 0;
System.out.println("\nRegister 2 (2 items)");
while (count3 < 2) {
System.out.print("Item price: £");
double price = scan.nextDouble();
reg3.addItem(price);
count3++;
}
System.out.println("\nFirst register. Total price: £" + reg1.getTotal() + "p for " + reg1.getItemCount() + " items");
System.out.println("Second register. Total price: £" + reg2.getTotal() + "p for " + reg2.getItemCount() + " items");
System.out.println("Third register. Total price: £" + reg3.getTotal() + "p for " + reg3.getItemCount() + " items");
}
}
It works fine except that if I enter all 1.00 I get this output:
Register 1 (2 items)
Item price: £1.00
Item price: £1.00
Register 2 (2 items)
Item price: £1.00
Item price: £1.00
Register 2 (2 items)
Item price: £1.00
Item price: £1.00
First register Total price: £2.0p for 2 items
Second register Total price: £2.0p for 2 items
Third register Total price: £2.0p for 2 items
Why am I getting £2.0 instead of £2.00?
I wrote this separately and it works absolutely fine:
public static void main(String[] args) {
double x = 100;
double y = 100;
double z = x + y;
String roundOff = String.format("%.2f", z);
System.out.println(roundOff);
}
Output:
200.00
Process finished with exit code 0
Why can't I get £2.00 in the exercise? Many thanks for any time taken to read all this :p
This is because your method getTotal has a return type of double but while concatenating the value in System.out.println you don't use formatting.
public double getTotal() {
String roundOff = String.format("%.2f", ((totalPrice * 100) / 10000));
double newDecimal;
newDecimal = Double.parseDouble(roundOff);
return newDecimal;
}
You should either return the formatted string from above method or change the print statements as follows:
System.out.println("\nFirst register. Total price: £" + String.format("%.2f", ((reg1.getTotal() * 100) / 10000)) + "p for " + reg1.getItemCount() + " items");
System.out.println("Second register. Total price: £" + String.format("%.2f", ((reg2.getTotal() * 100) / 10000)) + "p for " + reg2.getItemCount() + " items");
System.out.println("Third register. Total price: £" + String.format("%.2f", ((reg3.getTotal() * 100) / 10000)) + "p for " + reg3.getItemCount() + " items");
Note that a formatter has now been applied to the return value that you get from the method getTotal().
For a better reusability you should outline the first line in the method getTotal() in a new method like getTotalFormatted(). So you can use it in your rounding-algorithm and for printing too.
All of my main methods take place in this class:
package wk2individual;
import java.util.Scanner;
public class Wk2Individual {
public static void main(String[] args) {
AnnualPayCalculator aPC = new AnnualPayCalculator();
SalesPerson sP = new SalesPerson();
//System greeting
Scanner sc = new Scanner (System.in);
System.out.println ("Welcome to the Employee Annual Pay calculator!");
//user input
System.out.println("Please enter the name of the first sales employee:");
sP.salesPerson1 = sc.next();
System.out.println ("Please enter " + sP.salesPerson1 + "'s total sales for the year:");
aPC.totalSales1 = sc.nextDouble();
//begin outputs
if (aPC.totalSales1 >= 112000 && aPC.totalSales1 < 140000) {
System.out.println(sP.salesPerson1 + " has earned $" + aPC.total1() + " in "
+ "commissions for the year! " + sP.salesPerson1 + "'s total pay for the "
+ "year will be $" + aPC.total2()); //outputs employees commission and pay if sales meet incentive
}
else if (aPC.totalSales1 >= 140000) {
System.out.println(sP.salesPerson1 + " has earned $" + aPC.total3() + " in "
+ "commissions for the year! " + sP.salesPerson1 + "'s total pay for the "
+ "year will be $" + aPC.total4()); //outputs employees commission and pay if sales exceed targetSales
}
else if (aPC.totalSales1 < 112000) {
System.out.println(sP.salesPerson1 + " will receive a total pay of $" +
aPC.fixedSalary + " for the year. " + sP.salesPerson1 + " did not meet "
+ "the sales incentive to earn commission for the year."); /*outputs employees end of year pay as fixed
salary since the sales amount is less than 80% of the sales target*/
}
//begin the inputs for the second salesperson
System.out.println("Now let's get the name of the second sales employee:");
sP.salesPerson2 = sc.next();
System.out.println("Please enter " + sP.salesPerson2 + "'s total sales for the year:");
aPC.totalSales2 = sc.nextDouble();
//begin outputs
if (aPC.totalSales2 >= 112000 && aPC.totalSales2 < 140000) {
System.out.println(sP.salesPerson2 + " has earned $" + aPC.total5() + " in "
+ "commissions for the year! " + sP.salesPerson2 + "'s total pay for the "
+ "year will be $" + aPC.total6()); //outputs employees commission and pay if sales meet incentive
}
else if (aPC.totalSales2 >= 140000) {
System.out.println(sP.salesPerson2 + " has earned $" + aPC.total7() + " in "
+ "commissions for the year! " + sP.salesPerson2 + "'s total pay for the "
+ "year will be $" + aPC.total8()); //outputs employees commission and pay if sales exceed targetSales
}
else if (aPC.totalSales2 < 112000) {
System.out.println(sP.salesPerson2 + " will receive a total pay of $" +
aPC.fixedSalary + " for the year. " + sP.salesPerson2 + " did not meet "
+ "the sales incentive to earn commission for the year."); /*outputs employees end of year pay as fixed
salary since the sales amount is less than 80% of the sales target*/
}
//This is where I am trying to print the array created in the SalesPerson class
System.out.println("");
System.out.println("Here are both employee's sales in comparison:");
System.out.println(sP.salesPerson1 + "\t" + sP.salesPerson2);
System.out.print(n);
}
}
I created the AnnualPayCalculator class to hold the totals and calculations:
package wk2individual;
public class AnnualPayCalculator
{
double totalSales1, totalSales2, employee1TotalPay, employee2TotalPay;
double fixedSalary = 75000.00;
final double commissionRate = .25;
double salesTarget = 140000;
double accelerationFactor = .3125;
double total1(){
double incentiveCommission = totalSales1 * commissionRate;
return incentiveCommission;
}
double total2(){
double employee1TotalPay = total1() + fixedSalary;
return employee1TotalPay;
}
double total3(){
double targetCommission = totalSales1 * accelerationFactor;
return targetCommission;
}
double total4(){
double employee1TotalPay = total3() + fixedSalary;
return employee1TotalPay;
}
double total5(){
double incentiveCommission = totalSales2 * commissionRate;
return incentiveCommission;
}
double total6(){
double employee2TotalPay = total5() + fixedSalary;
return employee2TotalPay;
}
double total7(){
double targetCommission = totalSales2 * accelerationFactor;
return targetCommission;
}
double total8(){
double employee2TotalPay = total7() + fixedSalary;
return employee2TotalPay;
}
}
Then I created this SalesPerson class in which holds my array:
package wk2individual;
public class SalesPerson {
String salesPerson1, salesPerson2;
public static void main(String[] args) {
AnnualPayCalculator aPC = new AnnualPayCalculator();
Double[][] sales = new Double[2][2];
sales[0][0] = aPC.totalSales1;
sales[0][1] = aPC.totalSales2;
sales[1][0] = aPC.employee1TotalPay;
sales[1][1] = aPC.employee2TotalPay;
printArray(sales);
};
private static void printArray(Double[][] numbers){
for (Double[] n : numbers){
System.out.print(n);
}
}
In the first class I am able to print the totals of the calculations defined in the AnnualPayCalculator class. How can I print the array in the first class?
You probably don't want 2 main methods. When you create an object of SalesPerson in Wk2Individual, the 2d array sales is not being declared because static methods and variables are not part of instances/objects of classes. So what you might want to do is make a non-static method in SalesPerson like this;
public class SalesPerson {
String salesPerson1, salesPerson2;
public void createSales(AnnualPayCalculator aPC) {
// you don't need to create aPC
// AnnualPayCalculator aPC = new AnnualPayCalculator();
Double[][] sales = new Double[2][2];
sales[0][0] = aPC.totalSales1;
sales[0][1] = aPC.totalSales2;
sales[1][0] = aPC.employee1TotalPay;
sales[1][1] = aPC.employee2TotalPay;
printArray(sales);
}
}
Also, you are probably trying to use the values from the aPC object in the Wk2Individual class. But you are creating a new instance of the object instead. So you should pass the old aPC object from Wk2Individual class like this:
System.out.println("");
System.out.println("Here are both employee's sales in comparison:");
System.out.println(sP.salesPerson1 + "\t" + sP.salesPerson2);
sP.createSales(aPC);
This will send the aPC object with all the calculated values to the createSales() of SalesPerson class where your 2d array will be created.
Now you need to print this. To do that create a print method in the SalesPerson class:
private void printArray(Double[][] numbers){
for (Double[] n : numbers){
System.out.print(n);
}
}
But you cannot print an array like that. So do this:
System.out.println(Arrays.toString(n));
In AnnualPayCalculator class you have several methods which use the global variables: employee1TotalPay and employee2TotalPay. For example, the method total2(). In these methods, you are creating yet another variable with the same name. In total2() you are creating employee1TotalPay which shadows the global variable employee1TotalPay. It means that if inside that method you use employee1TotalPay anywhere, it will use the local employee1TotalPay variable (the one you created inside the method). To use the global variable either remove the declaration of the local variable:
employee1TotalPay = total1() + fixedSalary;
or use the this keyword to access the global variables:
this.employee1TotalPay = total1() + fixedSalary;
this is my first question here, so here it goes, I have tried this for ages with no luck, I am new to Java (studying it) and I have an assignment and I cant get this to work (only the first part works)...thanks in advanced for any help you can give me! :)
**Write a program to read in a non-specified number of Employee Salaries from the user. After each Employee Salary is entered the program should then calculate the Bonus for each employee. The bonus is to be calculated as a percentage of the Salary, according to the table shown below:
Salary Bonus Rate
Less than €10,000 5%
Between €10,000 and less than €20,000 10%
Between €20,000 and less than €30,000 15%
€30,000 or more 20%
The Program should output the Bonus Rate, Bonus Amount, and Total Salary for each Employee after the salary is entered.
When the user has entered the details for all employees, the program should then output the following:
Overall Total Bonuses paid
Overall Total Salaries paid (including bonuses)
Average Bonus
Your program should let the user indicate that they have finished entering results.
Add extra checks to your program so that negative figures are rejected by the program along with a suitable error message.
Test your program thoroughly, so that it works under all possible conditions.
Input/Output from the program should be attractively displayed on the screen.
import java.util.Scanner;
class Salary
{
public static void main (String args [])
{
Scanner myInput = new Scanner (System.in);
double salary =0, bonusRate =0, bonusAmount=0, salaryTotal=0, totalBonus=0, averageBonus=0, totalSalaries=0;
int salaryCounter=0;
char response;
do
{
System.out.println("Press a to enter a salary or press 'q' to quit");
response=myInput.next().charAt(0);
switch(response)
{
case 'a':
do
{
System.out.println("Enter employee salary or press q to quit");
salary = myInput.nextDouble();
if (salary <=0)
{
System.out.println("Invalid entry please enter Salary again ");
}
else if (salary >0 && salary <=10000)
{
System.out.println("*************************************************************");
System.out.println("The bonus rate is 5%");
bonusRate = salary * .05;
System.out.println("The bonus is " + bonusRate);
salaryTotal= salary + bonusRate;
System.out.println("The Total salary " + salaryTotal);
salaryCounter=salaryCounter+1;
System.out.println("*************************************************************");
}
else if (salary >10000 && salary <=20000)
{
System.out.println("*************************************************************");
System.out.println("The bonus rate is 10%");
bonusRate = salary * .10;
System.out.println("The bonus is " + bonusRate);
salaryTotal= salary + bonusRate;
System.out.println("The Total salary " + salaryTotal);
salaryCounter=salaryCounter+1;
System.out.println("*************************************************************");
}
else if (salary >20000 && salary <=30000)
{
System.out.println("*************************************************************");
System.out.println("The bonus rate is 15%");
bonusRate = salary * .15;
System.out.println("The bonus is " + bonusRate);
salaryTotal= salary + bonusRate;
System.out.println("The Total salary " + salaryTotal);
salaryCounter=salaryCounter+1;
System.out.println("*************************************************************");
}
else if (salary >30000)
{
System.out.println("*************************************************************");
System.out.println("The bonus rate is 20%");
bonusRate = salary * .20;
System.out.println("The bonus is " + bonusRate);
salaryTotal= salary + bonusRate;
System.out.println("The Total salary " + salaryTotal);
salaryCounter=salaryCounter+1;
System.out.println("*************************************************************");
}
//else
//{ //do i need to get rid of this?
// System.out.println("");
//}
}while(salary <=0);{
break;
}case 'q':
salaryCounter = salaryCounter+1;
bonusAmount= salary*bonusRate;
salaryTotal=salary+bonusAmount;
totalBonus=totalBonus+bonusAmount;
totalSalaries=totalSalaries+salaryTotal;
averageBonus=totalBonus*salaryCounter;
System.out.printf("The Total Salaries paid including Bonus is %.2f " , totalSalaries);
System.out.println("Euro");
System.out.printf("The Total of Bonuses paid is %.2f ", totalBonus);
System.out.println("Euro");
System.out.printf("The Total of Average Bonuses paid is %.2f ", averageBonus);
System.out.println("Euro");
break;
}//end do
//end switch
}while (response != 'q');{
//do while loop to repeat until 'q' is entered.
} //end do while loop
}//end main
}//end class
You can create two different files for your requirements: one pojo class containing the attributes of the employee and second main app where the user interacts with the program.
Salary.java
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
public class Salary {
private static int count = 0;
private int empId;
private double salary;
private int bonusRate;
private double bonusAmount;
private double totalSalary;
//Getters and Setters
public int getEmpId() {
return empId;
}
public double getTotalSalary() {
return totalSalary;
}
public void setTotalSalary(double totalSalary) {
this.totalSalary = totalSalary;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public int getBonusRate() {
return bonusRate;
}
public void setBonusRate(int bonusRate) {
this.bonusRate = bonusRate;
}
public double getBonusAmount() {
return bonusAmount;
}
public void setBonusAmount(double bonusAmount) {
this.bonusAmount = bonusAmount;
}
//Constructors
public Salary(int empId, double salary, int bonusRate, double bonusAmount,
double totalSalary) {
super();
this.empId = empId;
this.salary = salary;
this.bonusRate = bonusRate;
this.bonusAmount = bonusAmount;
this.totalSalary = totalSalary;
}
public Salary() {
super();
count = count + 1;
this.empId = count;
}
//toString
#Override
public String toString() {
return "Salary [empId=" + empId + ", salary=" + salary + ", bonusRate="
+ bonusRate + ", bonusAmount=" + bonusAmount + ", totalSalary="
+ totalSalary + "]";
}
//calculation function
public void calculateBonus(){
double bonus;
if(this.getSalary()<10000){
this.setBonusRate(5);
bonus = this.getSalary() + 0.05*(this.getSalary());
}else if(this.getSalary()<20000){
this.setBonusRate(10);
bonus = this.getSalary() + 0.10*(this.getSalary());
}else if(this.getSalary()<30000){
this.setBonusRate(15);
bonus = this.getSalary() + 0.15*(this.getSalary());
}else{
this.setBonusRate(20);
bonus = this.getSalary() + 0.20*(this.getSalary());
}
this.setBonusAmount(bonus);
this.setTotalSalary(this.getSalary() + bonus);
}
}
MainApp.java
import java.util.ArrayList;
import java.util.Scanner;
public class MainApp {
public static void main(String[] args) {
ArrayList<Salary> salaries = new ArrayList<Salary>();
Scanner sc = new Scanner(System.in);
String op = "y";
do {
Salary salary = new Salary();
System.out.println("Please Enter Salary for User "
+ salary.getEmpId() + " :");
salary.setSalary(sc.nextDouble());
salary.calculateBonus();
System.out.println(salary);
salaries.add(salary);
System.out.println("Do you want to enter more salaries: ");
op = sc.next();
} while (op.equals("y"));
double totalSalaries = 0;
double totalBonus = 0;
double averageBonus = 0;
int numberOfSalaries = 0;
for (Salary salary : salaries) {
System.out.println("Empid: " + salary.getEmpId() + " Salary: "
+ salary.getSalary() + " Bonus Rate: "
+ salary.getBonusRate() + " Bonus Amount: "
+ salary.getBonusAmount() + " Total Salary: "
+ salary.getTotalSalary());
totalSalaries = totalSalaries + salary.getTotalSalary();
totalBonus = totalBonus + salary.getBonusAmount();
numberOfSalaries = numberOfSalaries + 1;
}
averageBonus = totalBonus / numberOfSalaries;
System.out.println("Total Salaries for all employees: " + totalSalaries
+ " Total Bonuses: " + totalBonus
+ " Average Bonuses for all employees: " + averageBonus);
}
}
The code shall suffice your requirements.
I am supposed to add a toString method to the banckAccount class.
It should return a name separated by a comma and a space. Ex: "Yana" and balance of 3.03 , the call yana.toString() should return the string "Yana, $3.03".
I tried to add:
public String toString() {
return name + ", " + "$"+ balance;
}
It works when I type in:
"user, $90.01"
But when I enter
"Bankrupt Government, -$765432.10"
I keep getting:
"Bankrupt Government, $-765432.1"
Code:
import java.util.*;
public class BankAccount {
String name;
double balance;
public void deposit (double amount ){
balance = balance + amount;
}
public void withdraw ( double amount) {
balance = balance - amount ;
}
}//end of class
Your answer is right here:
return name + ", " + "$"+ balance;
Java simply concatenates the string as you have defined it. So if balance is a negative number, you will get $, followed by a negative number.
If you want it to display the - in the proper place, you can do something like this:
String sign = (balance < 0) ? "-" : "";
System.out.println(name + ", " + sign + "$" + Math.abs(balance));
Your balance is negative so it prints as listed. It needs to be
if(balance < 0){
balance = balance * -1;
return name + ", " + "-$"+ balance;
}
else{
return name + ", " + "$"+ balance;
}
It is quite obvious, what your method toString() is doing. If balance is negative, it is just added to the string with "-" sign after the "$". I would detect, if the balance is positive or not:
private String toString() {
if (balance > 0.0) {
return name + ", " + "$" + balance;
} else {
return name + ", -$" + (balance * (-1));
}
}
Or
private String toString() {
return name + ", " +
balance > 0.0 ? ("$" + balance) : ("-$" + (balance * (-1)));
}
hope this helps run this program
import java.util.*;
import java.io.*;
public class HelloWorld{
public String toString() {
if(balance<0)
{
balance= Math.abs(balance);
return name + ", " +"-"+ "$"+ balance;
}else
{
return name + ", " + "$"+ balance;
}
}
String name="sachin";
double balance=-1000.00;
public void deposit (double amount ){
balance = balance + amount;
}
public void withdraw ( double amount) {
balance = balance - amount ;
}
public static void main(String []args){
// System.out.println("Hello World");
HelloWorld helloWorld = new HelloWorld();
System.out.println(helloWorld.toString());
}
}
Hi I am new to Java programming. Why are my values returning null after I enter them on the input dialog. I have two classes, one called VehicleApp and the other called VehicleFactory. Help would be appreciated. Thanks.
Full code VehicleApp.java
package romprojectname;
import java.text.NumberFormat;
import javax.swing.JOptionPane;
public class VehicleApp{
public static void main(String[] args) {
String firstname = JOptionPane.showInputDialog("Enter your first name");
String lastname = JOptionPane.showInputDialog("Enter your last name");
long phone = Long.parseLong(JOptionPane.showInputDialog("Enter your phone"));
int nbrVehicles = Integer.parseInt(JOptionPane.showInputDialog("Enter number of vehicles"));
int nbrTanks = Integer.parseInt(JOptionPane.showInputDialog("Enter number of tanks"));
VehicleFactory vehicleObject = new VehicleFactory();
vehicleObject.getSummary();
vehicleObject.HayloFactory(firstname, lastname, phone, nbrVehicles, nbrTanks);
vehicleObject.calcFuelTankCost();
vehicleObject.calcManufacturingCost();
vehicleObject.calcSubtotal();
vehicleObject.calcTax();
vehicleObject.calcTotal();
}
}
Full code VehicleFactory.java
package romprojectname;
import java.text.NumberFormat;
import javax.swing.JOptionPane;
public class VehicleFactory{
private String firstname;
private String lastname;
private Long phone;
private int nbrVehicles =0;
private int nbrTanks =0;
private double manufactureCost =0;
private double fuelTankCost =0;
private double subtotal =0;
private double tax =0;
private double total = 0;
private final double VEHICLE_PRICE = 500.19;
private final double FUELCELL_PRICE = 2.15;
private final int CELLS_PER_TANK = 12;
private final double taxrate = 7.25 / 100 ;
public void HayloFactory(String firstname, String lastname, Long phone, int nbrVehicles, int nbrTanks){
this.firstname = firstname;
this.lastname = lastname;
this.phone = phone;
this.nbrVehicles = nbrVehicles;
this.nbrTanks = nbrTanks;
}
public void calcManufacturingCost(){
double manufactureCost = nbrVehicles * VEHICLE_PRICE;
}
public void calcFuelTankCost(){
double fuelTankCost = nbrVehicles * nbrTanks * CELLS_PER_TANK * FUELCELL_PRICE;
}
public void calcSubtotal(){
double subtotal = manufactureCost + fuelTankCost;
}
public void calcTax(){
double tax = subtotal * taxrate;
}
public void calcTotal(){
double total = subtotal + tax;
}
NumberFormat cf = NumberFormat.getCurrencyInstance();
public void getSummary(){
String summary = "WELCOME TO HAYLO MANUFACTURING" + "\n" + "\n";
summary += "Customer Name: " + firstname + " " + lastname + "\n";
summary += "Customer Phone: " + phone + "\n";
summary += "Number of Vehicles: " + nbrVehicles + "\n";
summary += "Number of Tanks: " + nbrTanks + "\n";
summary += "Vehicle Cost ($500.19 / vehicle): " + cf.format(manufactureCost) + "\n";
summary += "Tanks Cost ($2.15 / fuel cell): " + cf.format(fuelTankCost) + "\n";
summary += "Subtotal: " + cf.format(subtotal) + "\n";
summary += "Tax (7.25%): " + cf.format(tax) + "\n";
summary += "Total: " + cf.format(total) + "\n";
//display the summary
JOptionPane.showMessageDialog(null, summary);
}
}
Problem (code taken from VehicleFactory.java)
All of the summaries such as customer name are returning null values and all the costs and totals are $0.00.
public void getSummary(){
String summary = "WELCOME TO HAYLO MANUFACTURING" + "\n" + "\n";
summary += "Customer Name: " + firstname + " " + lastname + "\n";
summary += "Customer Phone: " + phone + "\n";
summary += "Number of Vehicles: " + nbrVehicles + "\n";
summary += "Number of Tanks: " + nbrTanks + "\n";
summary += "Vehicle Cost ($500.19 / vehicle): " + cf.format(manufactureCost) + "\n";
summary += "Tanks Cost ($2.15 / fuel cell): " + cf.format(fuelTankCost) + "\n";
summary += "Subtotal: " + cf.format(subtotal) + "\n";
summary += "Tax (7.25%): " + cf.format(tax) + "\n";
summary += "Total: " + cf.format(total) + "\n";
//display the summary
JOptionPane.showMessageDialog(null, summary);
You haven't really described the problem, but I suspect this is the cause:
VehicleFactory vehicleObject = new VehicleFactory();
vehicleObject.getSummary();
vehicleObject.HayloFactory(firstname, lastname, phone, nbrVehicles, nbrTanks);
You're calling getSummary before you call HayloFactory - so it's trying to display the values in the object before you've set them to useful values.
Additionally, all your calcXyz methods are introducing new local variables, like this:
public void calcTotal(){
double total = subtotal + tax;
}
Instead, they should be setting the field values:
public void calcTotal(){
total = subtotal + tax;
}
If you change all of your calculation methods appropriately, then move the getSummary() call to the very end, it will work. (It's not quite how I'd have written the code, but that's a different matter.)
The variables defined insides your methods have local scope only for example
double manufactureCost = nbrVehicles * VEHICLE_PRICE; it actually hides your class variable manufactureCost .. they should be instead used as
manufactureCost = nbrVehicles * VEHICLE_PRICE;
This way you can actually set the class variable which in turn displayed inside your getSummary method