Task Description
I have this problem statement:
Create a class Employee with the following private member variables.
int employeeId
String employeeName
double salary
double netSalary
Include appropriate getters and setters method in Employee class. Write the following method in the Employee class:
public void calculateNetSalary(int pfpercentage) - This method should take PF percentage as argument. Deduct the PF amount from the salary and set the netSalary.
Create a Main class which has the main method which invokes the method to get the input and prints the details as shown in the sample.
Also write a method :
public static Employee getEmployeeDetails() - which gets the employee details - id, name and salary, and returns the employee object.
public static int getPFPercentage() - which gets the PF percentage and returns the same
In the main method invoke the above two methods, and then call the calculateNetSalary method in Employee class and print the output as shown below.
Sample Input 1:
Enter Id:
101
Enter Name:
Vivek
Enter salary:
20000
Enter PF percentage:
7
Sample Output 1:
Id : 101
Name : Vivek
Salary : 20000.0
Net Salary : 18600.0
What I have done
I wrote the getter & setters methods and calculateNetSalary() method in Employee.java. I am stuck in as what and how should I write in Main.java
Employee.java
public class Employee{
private int employeeId;
private String employeeName;
private double salary;
private double netSalary;
//setters
public void setEmployeeId(int employeeId){
this.employeeId=employeeId;
}
public void setEmployeeName(String employeeName){
this.employeeName=employeeName;
}
public void setSalary(double salary){
this.salary=salary;
}
public void netSalary(double netSalary){
this.netSalary=netSalary;
}
//getters
public int getEmployeeId(){
return employeeId;
}
public String getEmployeeName(){
return employeeName;
}
public double getSalary(){
return salary;
}
public double getNetSalary(){
return netSalary;
}
public void calculateNetSalary(int pfpercentage){
pfamount=salary*pfpercentage;
netSalary=salary-pfamount;
}
}
Main.java
import java.util.Scanner;
public class Main{
public staic void main(String[] args){
Scanner sc = new Scanner(System.in);
Employee emp = new Employee();
System.out.println("Enter Id:"+setEmployeeId(sc.nextInt()))
System.out.println("Enter Name:"+setEmployeeName(sc.next()));
System.out.println("Enter salary:"+setSalary(sc.nextDouble()));
System.out.println("Enter PF percentage:");
double pfpercentage = sc.nextDouble();
public static Employee getEmployeeDetails(){
}
public static int getPFPercentage(){
}
}
}
I am unable to complete Main.java as I am not sure what and how to write.
This should be your code:
public void main(String[] args){
Scanner sc = new Scanner(System.in);
Employee emp = new Employee();
emp.setEmployeeId(sc.nextInt());
emp.setEmployeeName(sc.next()) ;
emp.setSalary(sc.nextDouble());
System.out.println("Enter PF percentage:");
double pfpercentage = sc.nextDouble();
emp.calculateNetSalary(pfpercentage);
System.out.println("Salay is " + emp.getNetSalary());
}
Also please notice that you haven't defined the type of pfamount:
public void calculateNetSalary(double pfpercentage){
double pfamount=salary*pfpercentage;
netSalary=salary-pfamount;
}
You can't define another methods inside the main() method.
You can call other methods inside it (as much as you like).
You have a couple of issues in your code. Firstly looking at Employee.java, there are a couple of issues:
Your method to set netSalary is declared as public void netSalary(double netSalary), where it should rather be public void SetNetSalary(double netSalary)
The calculation in public void calculateNetSalary(int pfpercentage) looks incorrect. If you going to pass in a double (i.e. 2 to represent 2%) then you need to divide this by 100 to convert the number to percentage.
You need to declare variables if you going to use them (namelty pfamount needs to be declared as a double before you can assign something to it).
You'll probably need a public String toString() method, for printing out your employee object.
So you'll end up with something like this:
public class Employee{
private int employeeId;
private String employeeName;
private double salary;
private double netSalary;
//setters
public void setEmployeeId(int employeeId){
this.employeeId=employeeId;
}
public void setEmployeeName(String employeeName){
this.employeeName=employeeName;
}
public void setSalary(double salary){
this.salary=salary;
}
public void setNetSalary(double netSalary){
this.netSalary=netSalary;
}
//getters
public int getEmployeeId(){
return employeeId;
}
public String getEmployeeName(){
return employeeName;
}
public double getSalary(){
return salary;
}
public double getNetSalary(){
return netSalary;
}
public void calculateNetSalary(double pfpercentage) {
double pfamount = salary * (pfpercentage / 100);
netSalary = salary - pfamount;
}
#Override
public String toString() {
String output = new StringBuffer()
.append("Id: ").append(employeeId)
.append(System.lineSeparator()).append("Name: ").append(employeeName)
.append(System.lineSeparator()).append("Salary: ").append(salary)
.append(System.lineSeparator()).append("Net Salary: ").append(netSalary).toString();
return output;
}
}
The you also have a couple of issues with your Main.java:
You can't declare methods within methods.
This is not the correct way to implement java.util.Scanner ... System.out.println("Enter Id:"+setEmployeeId(sc.nextInt())). Essentially the Scanner portion needs to be separated from the System.out (remember the only thing System.out does is print out text, it does not wait for input from Scanner).
If I understand your question correctly, you need to move some of your logic out of your main method and into getEmployeeDetails() and getPFPercentage()
So you'll end up with something like this:
import java.util.Scanner;
public class EmployeeSalaryCalculation {
private Scanner scanner;
public EmployeeSalaryCalculation() {
scanner = new Scanner(System.in);
}
public Employee getEmployeeDetails() {
Employee employee = new Employee();
System.out.println("Enter Id:");
employee.setEmployeeId(scanner.nextInt());
System.out.println("Enter Name:");
employee.setEmployeeName(scanner.next());
System.out.println("Enter salary:");
employee.setSalary(scanner.nextDouble());
return employee;
}
public double getPFPercentage(){
System.out.println("Enter PF percentage:");
return scanner.nextDouble();
}
public static void main(String[] args) {
EmployeeSalaryCalculation employeeSalaryCalculation = new EmployeeSalaryCalculation();
Employee employee = employeeSalaryCalculation.getEmployeeDetails();
employee.calculateNetSalary(employeeSalaryCalculation.getPFPercentage());
System.out.println(employee.toString());
}
}
You've made a good start. However, there are a couple of syntax errors such as forgetting to end some statements with a semi-colon. Also, as far as I know, Java doesn't support nested methods, so you shouldn't have the methods getEmployeeDetails() and getPFPercentage() inside your main method. I have rearranged the code to correct that.
Other changes I made was to your Employee class, particularly the calculateNetSalary method. pfPercentage is divided by 100 before multiplication by salary. Also, the instance variable netSalary is set to be the local variable netSalary after it has been calculated using the appropriate setter method. The method netSalary has also been renamed to setNetSalary since that is more descriptive of what the method does.
I haven't made any other changes to your code other than completing the Main class according to specifications. If there's any other part of the code that needs clarification, you can leave a comment about that.
Main.java
import java.util.Scanner;
public class Main {
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args){
Employee newEmployee = getEmployeeDetails();
double pfPercentage = getPFPercentage();
System.out.println();
System.out.println("Confirm employee details: ");
System.out.println("Id : " + newEmployee.getEmployeeId());
System.out.println("Name : " + newEmployee.getEmployeeName());
System.out.println("Salary : " + newEmployee.getSalary());
newEmployee.calculateNetSalary(pfPercentage);
System.out.println("Net Salary : " + newEmployee.getNetSalary());
}
/**
* Gets the details of a new employee from user input
* #return the new {#link Employee}
*/
public static Employee getEmployeeDetails() {
Employee employee = new Employee();
System.out.println("Enter Id: ");
employee.setEmployeeId(scanner.nextInt());
System.out.println("Enter Name: ");
employee.setEmployeeName(scanner.next());
System.out.println("Enter salary: ");
employee.setSalary(scanner.nextDouble());
return employee;
}
/**
* Gets the PF percentage from user input
* #return the PF percentage
*/
public static double getPFPercentage(){
System.out.println("Enter PF percentage:");
double pfPercentage = scanner.nextDouble();
return pfPercentage;
}
}
Employee.java
public class Employee{
private int employeeId;
private String employeeName;
private double salary;
private double netSalary;
// Setters
public void setEmployeeId(int employeeId){
this.employeeId = employeeId;
}
public void setEmployeeName(String employeeName){
this.employeeName = employeeName;
}
public void setSalary(double salary){
this.salary = salary;
}
private void setNetSalary(double netSalary){
this.netSalary = netSalary;
}
// Getters
public int getEmployeeId(){
return employeeId;
}
public String getEmployeeName(){
return employeeName;
}
public double getSalary(){
return salary;
}
public double getNetSalary(){
return netSalary;
}
public void calculateNetSalary (double pfPercentage){
double pfAmount = salary * (pfPercentage / 100);
double netSalary = salary - pfAmount;
this.setNetSalary(netSalary);
}
}
Write a class, Manager, that extends MonthlyEmployee, and has another instance variables, bonus and an instance method, setBonus. Override the pay method and update TestEmployee accordinly.
3.Write a class, TestShapes, that creates an instance of each of our shape classes and prints it.
Related
I'm starting to get into coding. My formats are bad, but I wanna see first if my idea for the program works then correct it later on. This is program consists of the main class (Employee), then two subclasses that inherit from the main class (Part-Time and Full-Time employees) The code works but I encountered null in my employee's name output in this code or maybe I missed something. Any help, correction, or advice would be great! Thank you
Main Class
class Employee {
public String Name;
public void setName(String Name)
{
this.Name = Name;
}
public String getName()
{
return Name;
}
public void emp()
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter Name: ");
Name = scan.nextLine();
}
}
Subclass FullTimeEmployee
class FullTimeEmployee extends Employee {
private double monthlySalary;
Scanner scan = new Scanner(System.in);
public void setMonthSalary(double monthlySalary) {
this.monthlySalary = monthlySalary;
}
public double getMonthlySalary() {
return monthlySalary;
}
#Override
public void emp() {
System.out.println("Enter monthly salary: ");
monthlySalary = scan.nextDouble();
System.out.println("Name: " + getName());
System.out.println();
System.out.println("Monthly Salary: " + monthlySalary);
}
}
subclass PartTimeEmployee
public class PartTimeEmployee extends Employee {
Scanner scan = new Scanner(System.in);
private double ratePerHour;
private int hoursWorked;
private double wage;
public void setWage(double wage) {
this.wage = wage;
}
public double getWage() {
return wage;
}
#Override
public void emp() {
System.out.println("Enter rate per hour and no of hours worked separated by space: ");
ratePerHour = scan.nextDouble();
hoursWorked = scan.nextInt();
System.out.println("Name: " + getName());
wage = ratePerHour * hoursWorked;
System.out.println("Wage: " + wage);
}
}
RunEmployee
public class RunEmployee {
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
Employee emp1 = new Employee();
FullTimeEmployee fte = new FullTimeEmployee();
PartTimeEmployee pte = new PartTimeEmployee();
emp1.emp();
System.out.println("Press F for Full Time or P for Part Time: ");
char select = scan.nextLine().charAt(0);
if(select == 'F') {
fte.emp();
} else if (select =='P') {
pte.emp();
}
}
}
OUTPUT OF BOTH
Enter monthly salary:
500
Name: null
You only set name in the Employee parent class in the emp() method here:
public void emp() {
Scanner scan = new Scanner(System.in);
System.out.println("Enter Name: ");
Name = scan.nextLine(); // here!
}
And yes, you give your child classes the same method and override and call it, but you never call the parent's version of the method, the super.emp() method, and so the name field never gets set.
A solution would be to call the super.emp() in your overrides, but this isn't good as it breaks the "single responsibility principle". And Employee should be responsible for Employee data and behaviors, but shouldn't be also responsible for handling a Scanner object and getting direct input from the user. Also, there are potential dangers from creating multiple Scanner objects based on System.in.
Much better, get all I/O, all use of Scanner, out of the Employee class and its children. The I/O should be in the main method (for this code) and instead, set name in the Employee constructor, and by calling the super constructor in the child classes, or by directly calling .setName(...) on any instances created.
e.g.,
class Employee {
public String name;
public Employee(String name) {
this.name = name;
}
public Employee() {
this(null);
}
public void setName(String Name) {
this.Name = Name;
}
public String getName() {
return Name;
}
// get rid of this
/*
public void emp() {
Scanner scan = new Scanner(System.in);
System.out.println("Enter Name: ");
Name = scan.nextLine();
}
*/
}
public class FullTimeEmployee extends Employee {
private double monthlySalary;
// Scanner scan = new Scanner(System.in); // *** get rid of this!
public FullTimeEmployee(String name) {
super(name);
}
public FullTimeEmployee() {
super();
}
public void setMonthSalary(double monthlySalary) {
this.monthlySalary = monthlySalary;
}
public double getMonthlySalary() {
return monthlySalary;
}
/* // get rid of this!
#Override
public void emp() {
System.out.println("Enter monthly salary: ");
monthlySalary = scan.nextDouble();
System.out.println("Name: " + getName());
System.out.println();
System.out.println("Monthly Salary: " + monthlySalary);
}
*/
}
and then again, put all Scanner code in the main method.
Regarding variable public String Name;
As an aside, you will want to learn and use Java naming conventions. Variable names should all begin with a lower letter while class names with an upper case letter. Learning this and following this will allow us to better understand your code, and would allow you to better understand the code of others.
Also, avoid using public fields unless absolutely necessary. Better to make this field protected, or even better yet, make it private.
i'm a beginner, I barely know anything, I tired to do some classes and just mess around with methods, but for some reason the method wont print, also I'm really bad with arrays :(
main class :
public class Employees {
static Employee[] array =new Employee[3];
static int i=0;
public void insertEmployee(){
Scanner keyboard=new Scanner(System.in);
System.out.println("please fill in the information :");
System.out.println("name :");
String Name=keyboard.next();
System.out.println("ID :");
long ID=keyboard.nextLong();
System.out.println("Salary :");
double Salary =keyboard.nextDouble();
Citizen s2 =new Citizen(Name);
Employee E= new Employee(ID,s2,Salary);
array[i]=E;
}
public void main(String[] args) {
Employees m1=new Employees();
for ( i=0; i<3;++i){
Employees c1=new Employees();
c1.insertEmployee();
}
System.out.println("*****");
for (i=0;i<3;++i){
array[i].print();
}
}
}
second class :
public class Employee {
private Citizen employeeInfo =new Citizen();
private long employeeID;
private double employeeSalary;
Employee(long employeeID,Citizen employeeInfo ){
this.employeeID=employeeID;
this.employeeInfo=employeeInfo;
}
Employee(long employeeID,Citizen employeeInfo, double employeeSalary){
this.employeeID=employeeID;
this.employeeInfo=employeeInfo;
this.employeeSalary=employeeSalary;
}
void print(){
if (employeeSalary==0){
employeeSalary=-1;
}
System.out.println(employeeID+"-"+employeeInfo.getCitizenName()+"-"+employeeSalary);
}
}
and last one:
public class Citizen {
private String citizenName;
private long citizenID;
public Citizen(){
}
public Citizen(String Name){
this.citizenName=Name;
}
public Citizen(String citizenName,long citizenID){
this.citizenName=citizenName;
this.citizenID=citizenID;
}
public String getCitizenName(){
return citizenName;
}
public long getCitizenID(){
return citizenID;
}
}
thank you :)
It has to be public static void main(String[] args). The static is important
So I am working on this Payroll class, I need to create two employees, hours worked and hourly pay and the calculate salaries. Finally, I have to add 10 extra hours to one of the previously created employees and calculate and display the total payroll. I wrote the two classes and everything works perfect, but when I look at the total Payroll it does not take into consideration the added hours.
The output for totalPayRoll should be $2000 after increasing the hours but i still get $1750!
public class PayRoll {
static double getTotalPayRoll()
{
return TotalPayRoll;
}
public String employeeId;
public int hoursWorked;
public final double hourlyPay;
private static double TotalPayRoll;
private static double Salary;
public PayRoll (String theEmployeeId, int theHoursWorked,
double theHourlyPay)
{
this.employeeId = theEmployeeId;
this.hoursWorked = theHoursWorked;
this.hourlyPay = theHourlyPay;
Salary = hoursWorked*hourlyPay;
TotalPayRoll = TotalPayRoll + Salary ;
}
public String getTheEmployeeId()
{
return this.employeeId;
}
public int getTheHoursWorked()
{
return this.hoursWorked;
}
public double getTheHourlyPay()
{
return this.hourlyPay;
}
public double getSalary()
{
return PayRoll.Salary;
}
public void increase (int extraHours)
{
hoursWorked = (hoursWorked + extraHours);
}
public void changeTheHoursWorked (int amount)
{
hoursWorked = hoursWorked + amount;
}
public void calculateSalary()
{
Salary = hoursWorked*hourlyPay;
}
public void calculateTotalPayRoll()
{
TotalPayRoll= TotalPayRoll+Salary;
}
public void changeHours(int newHours)
{
hoursWorked = newHours;
}
}
And this is the main
public class Test {
public static void main(String[] args) {
// TODO code application logic here
Date d = new Date();
DateFormat df = DateFormat.getDateInstance( DateFormat.MEDIUM );
NumberFormat nf = NumberFormat.getCurrencyInstance();
System.out.println("\nPayroll For Week Ending " + df.format(d));
System.out.println("-------------------------------------");
PayRoll employee1 = new PayRoll("444-4444", 30, 25);
employee1.calculateSalary();
displaySalary(employee1, nf);
PayRoll employee2 = new PayRoll("555-5555", 20, 50);
employee2.calculateSalary();
displaySalary(employee2, nf);
System.out.println("Increase " + employee1.getTheEmployeeId() +
" by 10 hours");
employee1.changeTheHoursWorked(10); // 10 hours increase
employee1.calculateSalary();
displaySalary(employee1, nf);
System.out.println("Total payout amount.. " +
nf.format(PayRoll.getTotalPayRoll()));
}
public static void displaySalary(PayRoll e, NumberFormat nf)
{
System.out.println("Employee #: " + e.getTheEmployeeId());
System.out.println("Hours Worked: " + e.getTheHoursWorked());
System.out.println("Hourly Rate: " + e.getTheHourlyPay());
System.out.println("Your Salary is: " + e.getSalary());
System.out.println("---------------------------------\n");
}
}
In your class :
private static double TotalPayRoll;
private static double Salary;
Both are static members(class level members), so there will be only one copy of these members which will be shared among all the objects. Because TotalPayRoll and salary should be different for different payrolls so these should be non-static.
This is because you have static fields - make everything non-static
private static double TotalPayRoll; -> private double TotalPayRoll;
private static double Salary; -> private double Salary;
What is happening with static fields is
Firstly hoursWorked is set to 30
then
hoursWorked is set to 20
then
hoursWorked is increased by 10
Since you are declaring objects of your PayRoll class, you don't need to make an static members.
You can make your class like this
public class PayRoll {
//don't have to declare any member public since you have functions to return value
//don't need access specifier since they are private by default
String employeeId;
int hoursWorked;
double hourlyPay;
double TotalPayRoll=0; //you have to initialize it to zero
double Salary;
public PayRoll (String theEmployeeId, int theHoursWorked,
double theHourlyPay)
{
this.employeeId = theEmployeeId;
this.hoursWorked = theHoursWorked;
this.hourlyPay = theHourlyPay;
// Salary = hoursWorked*hourlyPay;
// TotalPayRoll = TotalPayRoll + Salary ;
//you do not need to do this since you have different functions for them
}
public double getTotalPayRoll()
{
return this.TotalPayRoll;
}
public String getTheEmployeeId()
{
return this.employeeId;
}
public int getTheHoursWorked()
{
return this.hoursWorked;
}
public double getTheHourlyPay()
{
return this.hourlyPay;
}
public double getSalary()
{
return this.Salary;
}
//don't need the increase method
public void changeTheHoursWorked (int amount)
{
hoursWorked += amount;
}
public void calculateSalary()
{
Salary = hoursWorked*hourlyPay;
}
public void calculateTotalPayRoll()
{
TotalPayRoll+=Salary;
}
//don't need the change hours function
}
Hope this helps :)
I am trying to rewrite the toString() to print names. I use getNm() from each employee in an arraylist of object employees. Employees have the parameters (pay, nm, hoursWorked, overtimeHours)
I have bolded the code I am focused on.
public class Main {
public static void main(String[] args){
workers workerlist = new workers();
workerlist.setNumberEmployees();
workerlist.instantiateEmployees();
System.out.println(workerlist.toString());
}
}
public class Employees extends workers{
public double pay;
public String nm;
public double hours;
public double overtime;
public Employees(double pay, String nm, double hoursWorked, double overtimeHours){
}
public double getPay(){
return pay;
}
public void setPay(double pay){
}
public String getNm(){
return nm;
}
public void setNm(String nm){
}
public double getHours(){
return hours;
}
public void setHours(double hours){
}
public double getOvertime(){
return overtime;
}
public void setOvertime(double overtime){
}
}
import java.util.ArrayList;
import java.util.Scanner;
public class workers{
public int employeenumber;
public String nm;
ArrayList<Employees> workerList = new ArrayList<Employees>();
Scanner input = new Scanner(System.in);
public void setNumberEmployees(){
System.out.println("How many employees do you have?");
employeenumber = input.nextInt();
}
public int getNumberEmployees(){
return employeenumber;
}
public void instantiateEmployees(){
for(int i=1; i<=employeenumber; i++){
workerList.add(new Employees(0.0, "nm", 0.0, 0.0));
}
}
public String toString(){
String st = "";
for(int i=0; i<employeenumber; i++){
**st += workerList.toString();**
// ".toString() is there to test the setting of parameters, I am interested in replacing this part.
}
return st;
}
}
Expected Output [Employee 1's name, Employee 2's name,... Employee n's name]
I think below code will give your expected result.
public class Main {
public static void main(String[] args) {
workers workerlist = new workers();
workerlist.setNumberEmployees();
workerlist.instantiateEmployees();
System.out.println(workerlist.toString()); //call toString to take workerlist
}
}
Override Employees toString method and do not forget update nm parameter in constructor
public class Employees extends workers {
public double pay;
public String nm;
public double hours;
public double overtime;
public Employees(double pay, String nm, double hoursWorked, double overtimeHours) {
this.nm = nm; //do not forget set value
}
public double getPay() {
return pay;
}
public void setPay(double pay) {
}
public String getNm() {
return nm;
}
public void setNm(String nm) {
}
public double getHours() {
return hours;
}
public void setHours(double hours) {
}
public double getOvertime() {
return overtime;
}
public void setOvertime(double overtime) {
}
#Override
public String toString() {
return getNm(); //Employees toString method will return nm
}
}
override toString method and call arraylist's toString method.
public class workers {
public int employeenumber;
public String nm;
ArrayList<Employees> workerList = new ArrayList<Employees>();
Scanner input = new Scanner(System.in);
public void setNumberEmployees() {
System.out.println("How many employees do you have?");
employeenumber = input.nextInt();
}
public int getNumberEmployees() {
return employeenumber;
}
public void instantiateEmployees() {
for (int i = 1; i <= employeenumber; i++) {
workerList.add(new Employees(0.0, "nm", 0.0, 0.0));
}
}
public String toString() {
return workerList.toString(); //no need to iterate on arraylist, Arraylist.toString method will call each Employees toString method.
}
}
Yusuf K. and Andrew Tobilko have answered your question correctly. Just to give you some hints to improve your classes a bit:
Why do you call Employees eventhough your class can represent a single employee; so I would call it Employee instead.
Why do you define the nm field twice? It is declared in Workers class from which the Employees class is derived.
setNumberEmployees() method does not comply with JavaBeans convention; it must be declared as
public void setNumberEmployees(final String noEmployees) {
employeenumber = noEmployees;
}
And the call to setNumberEmployees() should be done in the main() method as
public static void main(String[] args){
workers workerlist = new workers();
Scanner input = new Scanner(System.in);
workerlist.setNumberEmployees(input.nextInt());
workerlist.instantiateEmployees();
System.out.println(workerlist.toString());
}
And lastly, you are speaking about parameter(s). They are actually called fields or instance variable(s).
public String toString(){
String st = "";
for(int i=0; i < employeenumber; i++)
st += workerList.get(i).toString();
return st;
}
But this solution is not the best. I suggest you the next one:
public String toString(){
StringBuilder builder = new StringBuilder();
workerList.stream().map(Employees::toString).forEach(builder::append);
return builder.toString();
}
And, of course, you have to override toString() in the Employees class. For example,
#Override public String toString() {
return new StringJoiner(", ")
.add(Double.toString(pay))
.add(nm)
.add(Double.toString(hours))
.add(Double.toString(overtime))
.toString();
}
An error points to the word "new" when I try to compile this program. I'm trying to create 2 objects from the carOrder class and I'm havin troubles! I've had this problem with other programs before and I'm not sure why and it's killing me, please help!
import java.text.DecimalFormat;
import java.util.Scanner;
public class CarOrder
private String buyer;
private String carType;
private double cost;
private int quantity;
private boolean taxStatus;
private double discountedCost;
private double taxAmount;
// Default Constructor
public void carOrder()
{
}
// Constructor
public void CarOrder(String buy, String car, double cos, int quan, boolean tax)
{
buyer = buy;
carType = car;
cost = cos;
quantity = quan;
taxStatus = tax;
}
// Sets the company buying cars
public void setBuyer(String buy)
{
buyer = buy;
}
// Sets the car type being purchased
public void setCarType(String car)
{
carType = car;
}
// Sets cost of the cars being purchased
public void setCost(double cos)
{
cost = cos;
}
// Sets the quantity of cars being purchased
public void setQuantity(int quan)
{
quantity = quan;
}
// Sets tax status for the cars
public void setTaxStatus(boolean tax)
{
taxStatus = tax;
}
// Returns name of buyer to user
public String getBuyer()
{
return buyer;
}
// Returns type of car to user
public String getCarType()
{
return carType;
}
// Returns cost to user
public double getCost()
{
return cost;
}
// Returns quantity of cars to user
public int getQuantity()
{
return quantity;
}
// Returns tax status to user
public boolean getTaxStatus()
{
return taxStatus;
}
// Returns discounted cost to user
public double getDiscountedCost()
{
if (quantity > 10)
if (quantity > 20)
discountedCost = cost - cost * .10;
else
discountedCost = cost - cost * .05;
else
discountedCost = cost;
return discountedCost;
}
// Returns tax amount to users
public double getTaxAmount()
{
taxAmount = cost * .0625;
return taxAmount;
}
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
CarOrder speedy = new CarOrder("Speedy Rental", "Mini Cooper", 22150, 15, true);
CarOrder zip = new CarOrder("Zip Car Co.", "Ford Fusion", 27495, 6, true);
System.out.println("Enter first Buyer");
String buyer1 = keyboard.nextLine();
}
}
public void CarOrder(String buy, String car, double cos, int quan, boolean tax)
{
should be
public CarOrder(String buy, String car, double cos, int quan, boolean tax)
{
Constructor's don't have a return type, not even void.
Currently, you have a method named CarOrder in your class as it has a return type as void, which voilates the rules of custructor. If you remove void, then it'd a constructor as it has the same name as your class.
Same applies to your constructor with no-argsaswell.
public void CarOrder()
should be
public CarOrder()
you are missing a "{" right after public class CarOrder ... :)
When you don't declare a constructor, Java provides a default constructor that have no arguments. As you declared CarOrder(String buy, String car, double cos, int quan, boolean tax), the default constructor is not created anymore. You made a method called carOrder, that probably was an attempt to make a constructor with no arguments, but it has two problems:
it has a return type (void) and constructor doesn't have one
the name is different from the class (cardOrder isn't the same as CarOrder, since Java is case sensitive)
If you want to make a new CarOrder() call, just add the following code:
public CarOrder() {
//insert your implementation here
}
A constructor with a return type is treated as a method by the compiler.