First java class is the primary one which invokes other classes. I will copy the code for the two files. I cannot compile this code and I do not know why.
When I had the program in one file it ran fine, but the instructor wants it in two files. Can someone explain to me what I am doing, or did incorrectly?
File 1:
public class Wk2ToddFoughty {
public static void main(String[] args) {
SalaryCalc FinalSalaryCalc = new SalaryCalc();
FinalSalaryCalc.SalaryCalc();
}
}
File 2:
import java.util.Scanner;
class SalaryCalc {
Scanner in = new Scanner(System.in);
System.out.println("Enter your annual sales: $");
double sales = in.nextDouble();
double salary = 35000.00;
double commission = (sales * .015);
double totalSalary = salary + sales;
System.out.println("Your Salary + Commission is: $" + totalSalary );
}
It might be easier to understand if you kept to Java naming conventions - also see inline comments
public class Wk2ToddFoughty {
public static void main(String[] args) {
SalaryCalc myCalc = new SalaryCalc(); // SalaryCalc - name of class
// myCalc - name of object
myCalc.doCalc(); // doCalc - name of method (missing from your class)
}
}
// edit this class to add missing method
public class SalaryCalc {
public void doCalc () {
Scanner in = new Scanner(System.in);
System.out.println("Enter your annual sales: $");
double sales = in.nextDouble();
double salary = 35000.00;
double commission = (sales * .015);
double totalSalary = salary + sales;
System.out.println("Your Salary + Commission is: $" + totalSalary );
}
}
Your second file doesn't define a method called SalaryCalc. You should also honor standard Java naming practices, and keep input/output logic outside of your business classes.
import java.util.Scanner;
public class Wk2ToddFoughty {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter your annual sales: $");
SalaryCalc calc = new SalaryCalc(35000);
double totalSalary = calc.calcSalary(in.nextDouble());
System.out.println("Your Salary + Commission is: $" + totalSalary);
}
}
public class SalaryCalc {
private double salary;
public SalaryCalc(double salary) {
this.salary = salary;
}
public void calcSalary(double sales) {
double commission = sales * 0.015;
return salary + sales + commission;
}
}
Related
I tried searching for this answer and found several answers that were similar to what I am looking for, but I can't seem to apply the suggestions provided on unrelated data to my specific program.
I need to take this working code I have created (a program to calculate an employee's annual compensation) and adjust it in a way that shows two classes (per the instructions of my homework assignment). The output given is exactly what I want, I just need help to reorganize the code so there is more than the main class. Is this something I can get help with here?
Here is my working code:
public class AnnualCompensation {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//create salary variable and commission percentage variable
double salary = 60000;
double commissionPercentage = 0.06;
//create command output for the user to get directions to enter value
System.out.println("Enter total amount of sales for the year: ");
double value = input.nextDouble();
double totalCompensation = (value * commissionPercentage) + salary;
System.out.println("Your annual compensation is: " + "$" + totalCompensation);
}
}
Thanks in advance.
create a class Employee with salary and commissionPercentage as the fields.
In constructor take the salary and commision% of employee and initate the fields.
in this class Employee create a method which will take vavlue as input and will calculate the compensation and return it.
So from main create the instance of Employee class and call the calculateMethod.
I would structure it with these classes:
AnnualCompensationCalculator which will do the computation for you as a utility class, and
AnnualCompensation main class which would be focused on requesting for the user input (and would call the calculator).
Suppose you can move the logic inside new class.
AnnualCompensationCalculator.java
public class AnnualCompensationCalculator{
private static double commissionPercentage = 0.06;
public static double calculateCompensation(double sales ,double salary){
return((sales * commissionPercentage) + salary);
}
}
AnnualCompensation .java
public class AnnualCompensation {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//create salary variable and commission percentage variable
double salary = 60000;
//create command output for the user to get directions to enter value
System.out.println("Enter total amount of sales for the year: ");
double value = input.nextDouble();
System.out.println("Your annual compensation is: " + "$" + AnnualCompensationCalculator.calculateCompensation(value,salary));
}
}
Following Object Oriented Programming, I suggest you create a new class Employee that holds the salary and compensation percentage of an employee, which also has a method for calculating the compensation.
Like this:
class Employee {
private double salary;
private double commPercent;
public Employee(double salary, double commPercent) {
this.salary = salary;
this.commPercent = commPercent;
}
public double calculateCompensation(double totalSales) {
return (totalSales * commPercent) + salary;
}
/* Setters & Getters */
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public double getCommPercent() {
return commPercent;
}
public void setCommPercent(double commPercent) {
this.commPercent = commPercent;
}
}
Then have your main class use this Employee class to do all the work:
public class AnnualCompensation {
public static void main(String[] args) {
//Initialize an Employee object
Employee emp = new Employee(60000, 0.06);
//Create command output for the user to get directions to enter value
System.out.print("Enter total amount of sales for the year: ");
Scanner input = new Scanner(System.in);
double salesAmt = input.nextDouble();
//Calculate the compensation based on the user input then print it
System.out.println("Your annual compensation is: $"
+ emp.calculateCompensation(salesAmt));
}
}
for the assignment, an employee has a ID number, hourly wage and works a certain # of hours. i need to calculate the gross income from those 2 values and then based of that there is withholding from the pay, in my code i believe all that is there but when i test my program i can only calculate the pay that was earned, the withholding and net pay come as a value of 0. i would appreciate any help on the issue, thank you.
// an employee has an ID, get paid an amout hourly and work an amount of hours
// tax is withheld depending on gross pay
public class Employee
{
//withholding calculation
public Employee(String empId, double hrsWrk, double hrPay)
{
employeeId = empId;
hoursWorked = hrsWrk;
hourlyPay = hrPay;
}
// access methods
public String getEmployeeId()
{
return employeeId;
}
public double getHoursWorked()
{
return hoursWorked;
}
public double getHourlyPay()
{
return hourlyPay;
}
public double getWithholding()
{
return withholding;
}
public double getIncome()
{
double income = hourlyPay * hoursWorked;
return income;
}
public double getNetPay()
{
double netPay = income - withholding;
return netPay;
}
// mutator methods
public void setId(String empId)
{
employeeId = empId;
}
public void setHoursWorked(double hrsWrk)
{
hoursWorked = hrsWrk;
}
public void setHourlyPay(double hrPay)
{
hourlyPay = hrPay;
}
//withholding calculator based on income
public void calcWithholding()
{
if(income <= 0)
{
withholding = 0.0;
}
else if(income >0 && income <= 300.0)
withholding = income*10.0/100;
else if(income >= 300.01 && income <= 400.0)
withholding = income*12/100;
else if(income >= 400.01 && income <= 500.0)
withholding = income*15/10;
else
withholding = income*20/100;
System.out.println("withholding is " + withholding);
}
public void displayWithholding()
{
calcWithholding();
System.out.println("Employee " + employeeId + " your income is " + getIncome() + " per week\n you have to pay " + getWithholding());
System.out.println("Employee " + employeeId + " your net income is " + getNetPay());
}
//instance fields
private String employeeId;
private double hoursWorked;
private double hourlyPay;
private double withholding;
private double income;
private double netPay;
}
here is the test program---------------------------------------------
import javax.swing.JOptionPane;
public class EmployeeTest
{
public static void main(String[] args)
{
String employeeId = JOptionPane.showInputDialog("Please enter your Employee ID");
String input = JOptionPane.showInputDialog("Enter your hourly wage");
double hourlyPay = Double.parseDouble(input);
input = JOptionPane.showInputDialog("How many hours have you worked this week?");
double hoursWorked = Double.parseDouble(input);
Employee richard = new Employee(employeeId, hoursWorked, hourlyPay);
richard.displayWithholding();
System.exit(0);
}
}
You're not calling getIncome until after calcWithHolding so the income variable is always zero during the calculation.
The current approach relies on side-effects from calling some of the accessors, this is generally considered to be a bad approach.
I would suggest one of the following
Ensure calculations done in the constructor (or called...)
Separate your concerns so that there is no confusion between data storage, object construction, data accessors and calculations.
Lazy initialization, so that calculated values are only calculated if they have never been accessed.
I need some help with a program for my programming class. It's a recursive program that takes a subtotal and a gratuity rate given by the user that outputs the full total and the gratuity cost. This is what I've got so far, and for some reason it just doesn't work:
import java.io.*;
import java.until.Scanner;
public class gratuity {
private double total;
private double subTotal;
private double gratRate;
private double newSubTotal;
private double newGratRate;
public static void main(String[] args) {
System.out.print("Enter the subtotal: ");
System.out.print("Enter the gratuity rate: ");
Scanner scan = new Scanner(System.in);
Scanner myScan = new Scanner(System.in);
double subtotal = scan.nextDouble();
double gratRate = myScan.nextDouble();
System.out.println("The Gratuity is: " + newSubtotal);
System.out.println("The Total is: " + Total);
}
public static double computeGratRate() {
double newGratRate = (gratRate/100);
return newGratRAte;
}
public static double computeNewSub() {
double newSubTotal - (subTotal * newGratRate);
return newSubTotal;
}
public static double computeTotal() {
double total = (newSubTotal + newGratRate);
return total;
}
}
If anyone would help me figure out how to fix it, I would be very grateful! Thank you!
A few things.
You are creating new variables called "subtotal" and "gratRate" in Main. These values override the member variables of the class.
Your problem won't compile anyway, because...
All your methods are static, which is OK, but these static methods are accessing non-static variables. Make all your member variables of this class static. (Or make everything outside of Main not static and then have "Main" be a stub to just create an instance of the gratuity class.
You need to import java.util.Scanner, not java.until.Scanner.
This line is a compiler error:
double newSubTotal - (subTotal * newGratRate);
I think you mean:
double newSubTotal = (subTotal * newGratRate);
That should be enough hints for now.... keep trying.
Did you mean:
import java.util.Scanner;
public class Gratuity {
private double subTotal;
private double gratRate;
public static void main(String[] args) {
Gratuity gratuity = new Gratuity();
System.out.print("Enter the subtotal: ");
Scanner scan = new Scanner(System.in);
gratuity.setSubTotal(scan.nextDouble());
System.out.print("Enter the gratuity rate: ");
Scanner myScan = new Scanner(System.in);
gratuity.setGratRate(myScan.nextDouble());
System.out.println("The new GratRate is: " + gratuity.getNewGratRate());
System.out.println("The New Sub is: " + gratuity.getNewSub());
System.out.println("The Total is: " + gratuity.getTotal());
}
public double getNewGratRate() {
return gratRate/100;
}
public double getNewSub() {
return getNewGratRate() * subTotal;
}
public double getTotal() {
return getNewSub() + getNewGratRate();
}
public double getSubTotal() {
return subTotal;
}
public void setSubTotal(double subTotal) {
this.subTotal = subTotal;
}
public double getGratRate() {
return gratRate;
}
public void setGratRate(double gratRate) {
this.gratRate = gratRate;
}
}
I just started learning Java and I'm trying to write a program based on an assignment sheet (gave this sheet at bottom of the post). However, I really don't quite understand how to use methods all that well. I've written my methods in the "Customer.java" class, and I'm trying to use them in my "TestCustomer.java" class. However, since I really don't know how to do this, it has turned out horribly. I've searched for information on this, but I just seem to keep making myself more confused. Is there any chance you guys could show me the correct way to use these methods, or at least point me in the right direction? Thank you a ton for any help you can provide.
Customer class
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Customer {
public static double taxRate = 0.00;
public static double saleRate = 0.00;
String customerName;
double listSaleAmount;
double saleDiscount = 0;
double netSaleAmount;
double taxAmount;
double saleTotal;
boolean taxable;
public Customer (String CustomerName, boolean taxable) {
}
public double calculateTax (double listSaleAmount) {
saleDiscount = listSaleAmount*saleRate;
netSaleAmount = listSaleAmount-saleDiscount;
if (taxable == true) {
taxAmount = netSaleAmount*taxRate;
}
else {
taxAmount = 0.00;
}
saleTotal = listSaleAmount + taxAmount;
return saleTotal;
}
public String printRecord; {
System.out.println("Customer is " + customerName);
System.out.println("Sale amount is $" + listSaleAmount);
System.out.println("Discount amount is $" + saleDiscount);
System.out.println("Net Sale Amount is $" + netSaleAmount);
System.out.println("Tax amount is $" + taxAmount);
System.out.println("Total Sale Amount is $" + saleTotal);
}
public static double changeTaxAmount (double taxRate) {
Scanner input = new Scanner(System.in);
double userTaxAmount = Double.parseDouble(JOptionPane.showInputDialog("What is the Tax Rate? (8.25 & 8.50 for testing)"));
taxRate = userTaxAmount;
return taxRate;
}
public static double changeSaleRate (double saleRate) {
Scanner input = new Scanner(System.in);
double userSaleAmount = Double.parseDouble(JOptionPane.showInputDialog("What is the Sale Discount Rate? (0.00 & 7.50 for testing)"));
saleRate= userSaleAmount;
return saleRate;
}
public static String printTaxRate; {
System.out.println("Tax Rate is" + taxRate + "%.");
}
public static String printSaleRate; {
System.out.println("The Sale Rate is" + saleRate + ".");
}
}
TestCustomer class
import java.math.BigDecimal;
public class TestCustomer {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Customer customer1 = new Customer("Annie Smith", true);
Customer customer2 = new Customer("Bob Wilson", false);
Double totalOfAllSales = 0.00;
//I have no clue how to actually use the methods I created in the Customer class!
//These are my best guesses, which are obviously wrong
//Any help here would be greatly appreciated!
Customer.changeTaxAmount(taxRate);
Customer.printTaxRate;
Customer.changeSaleRate(saleRate);
Customer.printSaleRate;
customer1.listSaleAmount = 65.00;
customer2.listSaleAmount = 52.00;
totalOfAllSales += customer1.calculateTax;
totalOfAllSales += customer2.calculateTax;
customer1.printRecord;
customer2.printRecord;
Customer.changeTaxAmount(taxRate);
Customer.printTaxRate;
Customer.changeSaleRate(saleRate);
Customer.printSaleRate;
customer1.listSaleAmount = 84.00;
customer2.listSaleAmount = 105.00;
totalOfAllSales += customer1.calculateTax;
totalOfAllSales += customer2.calculateTax;
customer1.printRecord;
customer2.printRecord;
System.out.println("The total of all sales is $" + totalOfAllSales);
}
}
Assignment sheet (Not worrying about printing to a file right now, just want the main mechanics to work)
You seem to be confused about the syntax for calling a method. The syntax is as follows:
object.method(arguments)
If there are no arguments it looks like this:
object.method()
Also, you need to use accessor and mutator methods instead of directly setting instance variables like you do here:
customer1.listSaleAmount = 65.00;
You should implement methods like these:
public void setListSaleAmount(double lsa) {
listSaleAmout = lsa;
}
public double getListSaleAmount() {
return listSaleAmount;
}
and make listSaleAmount private.
Problem #2: The syntax for defining the methods. You are using this code to define a method:
public static String printTaxRate; {
System.out.println("Tax Rate is" + taxRate + "%.");
}
You should be using this code:
public static String printTaxRate() {
System.out.println("Tax Rate is" + taxRate + "%.");
}
The problem is the weirdly placed semicolon inside the method header.
I'm having a little bit of trouble with my code that I can't seem to figure out. Whenever I run this, it prints "Customer is null" instead of inserting their name. It also always calculates all tax as 0 (something wrong with my if statement?).
Is there any chance you guys can spot the issue? It seems as though everything else works correctly. (Wrote methods in Customer class, calling them in TestCustomer class, and the instructions are at the end of the post).
Thank you for anyone who takes the time to read this and attempt to help. Sorry for so much information, I just have no clue what is causing this, so I figured I'd include everything.
Customer class
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Customer {
public static double taxRate = 0.00;
public static double saleRate = 0.00;
String customerName;
double listSaleAmount;
double saleDiscount = 0;
double netSaleAmount;
double taxAmount;
double saleTotal;
boolean taxable;
public double total;
public Customer (String customerName, boolean taxable) {
}
public void calculateTax () {
saleDiscount = listSaleAmount*(saleRate/100);
netSaleAmount = listSaleAmount-saleDiscount;
if (taxable = true){
taxAmount = netSaleAmount*(taxRate/100);
}
else{
taxAmount = 0;
}
saleTotal = netSaleAmount + taxAmount;
total += saleTotal;
}
public void printRecord () {
System.out.println("Customer is " + customerName);
System.out.println("Sale amount is $" + listSaleAmount);
System.out.println("Discount amount is $" + saleDiscount);
System.out.println("Net Sale Amount is $" + netSaleAmount);
System.out.println("Tax amount is $" + taxAmount);
System.out.println("Total Sale Amount is $" + saleTotal);
System.out.println(" ");
}
public static void changeTaxAmount () {
Scanner input = new Scanner(System.in);
double userTaxAmount = Double.parseDouble(JOptionPane.showInputDialog("What is the Tax Rate? (8.25 & 8.50 for testing)"));
taxRate = userTaxAmount;
}
public static void changeSaleRate () {
Scanner input = new Scanner(System.in);
double userSaleAmount = Double.parseDouble(JOptionPane.showInputDialog("What is the Sale Discount Rate? (0.00 & 7.50 for testing)"));
saleRate= userSaleAmount;
}
public static void printTaxRate() {
System.out.println("Tax Rate is " + taxRate + "%.");
}
public static void printSaleRate() {
System.out.println("The Sale Rate is " + saleRate + ".");
System.out.println(" ");
}
}
TestCustomer class
public class TestCustomer {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Customer customer1 = new Customer("Annie Smith", true);
Customer customer2 = new Customer("Bob Wilson", false);
Customer.changeTaxAmount();
Customer.printTaxRate();
Customer.changeSaleRate();
Customer.printSaleRate();
customer1.listSaleAmount = 65.00;
customer2.listSaleAmount = 52.00;
customer1.calculateTax();
customer1.printRecord();
customer2.calculateTax();
customer2.printRecord();
Customer.changeTaxAmount();
Customer.printTaxRate();
Customer.changeSaleRate();
Customer.printSaleRate();
customer1.listSaleAmount = 84.00;
customer2.listSaleAmount = 105.00;
customer1.calculateTax();
customer1.printRecord();
customer2.calculateTax();
customer2.printRecord();
double total2 = customer1.total + customer2.total;
System.out.println("The total of all sales is $" + total2);
}
}
Assignment sheet (Not worrying about printing to a file right now, just want the main mechanics to work)
Also, thank you to those of you who helped me with my last question on this project. You helped a lot.
In your constructor
public Customer (String customerName, boolean taxable) {
}
You are passed in parameters, but you never assign them to your class fields.
try
public Customer (String customerName, boolean taxable) {
this.customerName = customerName;
this.taxable = taxable;
}
You have to define your constructor in customer class to set values of customerName and texable class level variables:
public Customer (String customerName, boolean taxable) {
this.customerName = customerName;
this.taxable = taxable;
}
Also, there seems to be problem with the below if condition:
if (taxable = true){
You should use == operator for comparing:
if (taxable == true) {
Actually, you don't need to compare it. Just use:
if (taxable) {
Your constructor in Customer class should assign the name and taxable value to Customer data member.
public Customer (String customerName, boolean taxable) {
this.customerName = customerName;
this.taxable = taxable;
}
Instead of using if (taxable = true), simply use if (taxable).