How to input the result of an instance into another instance - java

I am a beginner in java and I tried doing this activity but I am so confused on the determineClass instance. When I run the code below, the 'classification' is not called.
Instructions:
The computeWeekly method is an instance method that should compute the weekly salary using the formula: fixedSalary * daysWorked * bonusRate. Whatever the computed weekly salary is, the determineClass method takes the value as an input and determines what classification the employee is (use your conditional structure research here).
The displayEmployee method just prints out all the attributes of each object. Name, Classification, Fixed Salary, WeeklyGross, and Bonus Rate. The appropriate classification should be reflected depending on the computed weekly gross.
public class Employee{
public String name;
public char classification;
private double fixedSalary;
private double weeklyGross;
private double bonusRate;
//constructor without a parameter
public Employee(){
this.name = "Paul";
this.fixedSalary = 250;
this.bonusRate = 5;
}
//compute weekly salary
private double computeWeekly(double fixedSalary, int daysWorked, double bonusRate){
weeklyGross = fixedSalary * daysWorked * bonusRate;
return weeklyGross;
}
//take the weekly salary as input and determine what's the classification of the employee
private char determineClass(double computeWeekly){
if (computeWeekly >= 0){
classification = 'A';
}else if (computeWeekly >= 2000){
classification = 'B';
}else if (computeWeekly >= 2500){
classification = 'C';
}else if (computeWeekly >= 3000){
classification = 'D';
}else if (computeWeekly >= 3500){
classification = 'E';
}else{
classification = 'F';
}
return classification;
}
//display information
public void displayEmployee(){
System.out.println("Name: " + name);
System.out.println("Classification: " + classification);
System.out.println("Fixed Salary: " + fixedSalary);
System.out.println("Weekly Gross: " + weeklyGross);
System.out.println("Bonus Rate: " + bonusRate);
}
//main
public static void main(String[] args){
Employee employee1 = new Employee();
employee1.computeWeekly(300, 7, 10);
employee1.displayEmployee();
}
}
Result:
Name: Paul
Classification:
Fixed Salary: 250.0
Weekly Gross: 21000.0
Bonus Rate: 5.0
How can I set the value for the classification applying the conditional structure?

What is with
employee1.classification=employee1.determineClass(employee1.getWeeklyGross());
therefore you have to implement the function:
public double getWeeklyGross(){
return WeeklyGross;
}

You can set the value of classification with the following expression:
classification = determineClass(weeklyGross);
This has to be implemented between those two lines of code.
employee1.computeWeekly(300, 7, 10);
employee1.displayEmployee();

Related

Java inheritance / overriding method ISSUE

okay so to the preface the situation. I have been given an assignment with various tasks. So far I have created a Canteen Account(which will be shown below), a main menu class, and now I have to make another class which inherits from Canteen Account, called StaffAccount. A StaffAccount object should contain the following additional property :
discountRate - the rate (percentage) discount applied to all purchases
A StaffAccount object should contain the following additional methods:
(i) StaffAccount (String newId, String newName, double discountRate)
A constructor method to initialise the StaffAccount object’s properties via the three parameters.
In the staff account I am having issues with a method called PayForMeal(which is an overridden method) which in the assignment brief has the purpose of:
A method to record the cost of a meal. The balance on a StaffAccount object should be amended to reflect discount on the cost of a meal (if the cost does not exceed available balance).
If the cost exceeds the balance then an Exception will be thrown to warn the customer they must topUp their balance – if the customer is within their credit limit a negative value will be recorded in the balance and the status of the account changed to show that the customer is using credit.
No discount should be applied if the customer is using credit.
So my issue is, how do I make a staff account using the constructor given to me, and then use the payForMeal overridden method to apply a discount to the amount a meal costs, then take the discounted amount away from a balance which is not there because it is not in the constructor for the StaffAccount, but it is in the constructor for the CanteenAccount. The classes are below, i just want to know if this is possible or am I being dumb
//////CANTEEN ACCOUNT \\\\\\\\
public class CanteenAcc
{
private String customerId;
private String name;
private double balance;
private static double minTopup = 2.00;
private String status;
private static double creditLimit = 5.00;
private static int transCount;
/**
* Constructor to create a Canteen account object using three parameters
* #param newId - String
* #param newName - String
* #param newBalance - Double
*/
public CanteenAcc(String newId, String newName, double newBalance)
{
this.customerId = newId;
this.name = newName;
this.balance = newBalance;
}
public CanteenAcc(String newId, String newName)
{
this.customerId = newId;
this.name = newName;
}
//BEFORE EVERY METHOD AND CLASS YOU SHOULD HAVE JAVADOC COMMENTS.
public void topUp(double depositAmount)
{
if(depositAmount > 0)
{
this.balance += depositAmount;
this.status = "Valid";
}else
{
this.status = "Invalid";
}
}
public void payForMeal(double amount) throws Exception
{
if(balance - amount < 0 && amount - balance <= creditLimit)
{
this.status = "Using Credit";
double newBalance = balance - amount;
balance = newBalance;
throw new Exception("\n\n-----------------------------\n"
+ "You must top-up your balance\n"
+ "Your new balance is: "+ balance + " GBP" +"\n"
+ "You are: " + status + "\n"
+ "-----------------------------\n");
}
else if(amount > creditLimit && balance < amount)
{
throw new Exception("\n\n------------------------------\n"
+ "Cost exceeds the credit limit."
+ "\n------------------------------\n");
}
else
{
double newBalance = balance - amount;
balance = newBalance;
transCount++;
}
}
public String displayAccountDetails()
{
StringBuilder ad = new StringBuilder();
ad.append("------------------------\n");
ad.append("****Account Details****\n");
ad.append("------------------------\n");
ad.append("\n");
ad.append("****Customer ID****: \n" + customerId + "\n");
ad.append("\n");
ad.append("****Name****: \n" + name + "\n");
ad.append("------------------------\n");
ad.append("\n");
return ad.toString();
}
public String getStatistics()
{
StringBuilder as = new StringBuilder();
as.append("------------------------\n");
as.append(" CANTEEN ACCOUNT \n");
as.append("------------------------\n");
as.append("\n");
as.append("****Transaction Count****\n");
as.append(transCount + "\n");
as.append("\n");
as.append("****Account Balance****\n");
as.append(balance + "\n");
as.append("\n");
as.append("***Account Status****\n");
as.append(status + "\n");
as.append("------------------------\n");
return as.toString();
}
public double getBalance()
{
return balance;
}
public double getCreditLimt()
{
return creditLimit;
}
public double getMinTopup()
{
return minTopup;
}
public String getStatus()
{
return status;
}
public static void updateCreditLimit(double newLimit)
{
creditLimit = newLimit;
}
public static void updateMinTopup(double newTopup)
{
minTopup = newTopup;
}
}
////////MAIN METHOD////////////////////////
public class Test
{
public static void main(String[] args) {
String menuItems[] = {"1. Top up account ", "2. Pay for meal ", "3. Display Account Status",
"4. Display Account Balance ", "5. Display Account Details ",
"6. Update credit limit ", "7. Update Minimum top-up ", "8. Exit program"};
Menu myMenu = new Menu("Holiday Account", menuItems) ;
int choice;
Scanner keyb = new Scanner(System.in);
choice = myMenu.getChoice() ;
do{
choice = myMenu.getChoice();
//CanteenAcc Employee = new CanteenAcc("A01PL", "Patrick", 2);
CanteenAcc Employee2 = new StaffAccount("blah", "blah", 0.25);
switch (choice)
{
case 1 : System.out.println("How much would you like to top-up: ");
double deposit = keyb.nextDouble();
Employee2.topUp(deposit);
System.out.println("Your balance is: £" + Employee2.getBalance());
break ;
case 2: System.out.println("Input how much your meal costs: ");
try {
double amount = keyb.nextDouble();
Employee2.payForMeal(amount);
System.out.println("Your meal cost: " + amount);
} catch(Exception ex)
{
System.out.println(ex.toString());
}
System.out.println("Your balance is: £" + Employee2.getBalance());
break ;
case 3: System.out.println(Employee2.getStatus());
break;
case 4: System.out.println("£" + Employee2.getBalance());
break;
case 5: System.out.println(Employee.displayAccountDetails());
break;
case 6: System.out.println("What amount would you like the new limit to be: ");
double newLimit = keyb.nextDouble();
CanteenAcc.updateCreditLimit(newLimit);
System.out.println("The new credit limit is: " + newLimit);
case 7: System.out.println("What amount would you like the new limit to be: ");
double newMinTopup = keyb.nextDouble();
CanteenAcc.updateMinTopup(newMinTopup);
System.out.println("The new minimum topUp is: " + newMinTopup);
case 8: System.exit(0);
}
}//End DoWhile
while(choice != 8);
}
}
////STAFF ACCOUNT///////
public class StaffAccount extends CanteenAcc
{
private double discountRate;
public StaffAccount(String newId, String newName, double discountRate)
{
super (newId, newName);
this.discountRate = 0.25;
balance = 0;
}
public void setDiscountRate(double rate)
{
discountRate = rate;
}
public double getDiscountRate()
{
return discountRate;
}
public void payForMeal(double amount) throws Exception
{
amount = amount/discountRate;
super.payForMeal(amount);
}
}
OK:
You've got a CanteenAcc: good. You've also got a StaffAccount that inherits from CanteenAcc. Also good.
You should annotate StaffAccount.payForMeal() with #Override: When do you use Java's #Override annotation and why?
Your variable names should all start with lower case, e.g. CanteenAcc employee2 = new StaffAccount("blah", "blah", 0.25);.
updateCreditLimit() and updateMinTopup() should NOT be static (because each different object might have a different value): Java: when to use static methods
... Finally ...
With CanteenAcc employee = new CanteenAcc("A01PL", "Patrick", 2);, then employee.payForMeal() will have the "CanteenAcc" behavior.
With CanteenAcc employee2 = new StaffAccount("blah", "blah", 0.25);, then employee2.payForMeal() will have the "StaffAccount" behavior.
Q: So what's the problem? Does that help clarify ... or does it just confuse things further?
There are a number of things "wrong" with the code you posted. I hope you have an IDE, and step through the debugger with sample test values.
But to your original question:
You're on the right track.
There are a couple of "minor" issues I noted above.
I'm not sure why you're worried about "constructors". The way object oriented languages (like Java) work - if you define the right base classes, and appropriately "specialize" behavior in subclasses, then - through the magic of "inheritence" - everything "just works".
I modified your code slightly, and wrote a different "test driver". Here is the code, and the output:
StaffAccount.java
package com.example;
public class StaffAccount extends CanteenAccount {
private double discountRate;
public StaffAccount(String newId, String newName, double discountRate) {
super(newId, newName);
this.discountRate = discountRate; // Set this to "discountRate", instead of hard-coding 0.25
// You'll note that "balance" is implicitly set to "0.0" in the base class
}
public void setDiscountRate(double rate) {
discountRate = rate;
}
public double getDiscountRate() {
return discountRate;
}
#Override
public void payForMeal(double amount) throws Exception {
amount = amount / discountRate;
super.payForMeal(amount);
}
}
TestAccount.java
package com.example;
/**
* Test driver
* In a "real" application, I would implement these as a suite of JUnit tests
*/
public class TestAccount {
private static void buyAMeal (CanteenAccount person, double cost) {
try {
person.payForMeal(cost);
} catch (Exception e) {
System.out.println ("ERROR: " + e.getMessage());
}
}
public static void main(String[] args) {
System.out.println (">>Creating employee (\"CanteenAccount\" and employee2 (\"StaffAccount\") objects...");
CanteenAccount employee = new CanteenAccount("A01PL", "Patrick", 2);
CanteenAccount employee2 = new StaffAccount("blah", "blah", 0.25);
System.out.println (">>Checking initial balances...");
System.out.println (" employee balance=" + employee.getBalance() + ", creditLimit=" + employee.getCreditLimit());
System.out.println (" employee2 balance=" + employee2.getBalance() + ", creditLimit=" + employee2.getCreditLimit());
System.out.println (">>Buying a $5.00 meal...");
System.out.println (" employee...");
buyAMeal (employee, 5.00);
System.out.println (" employee balance=" + employee.getBalance() + ", creditLimit=" + employee.getCreditLimit());
System.out.println (" employee2...");
buyAMeal (employee2, 5.00);
System.out.println (" employee2 balance=" + employee2.getBalance() + ", creditLimit=" + employee2.getCreditLimit());
System.out.println (">>Add $5.00 and buy another $5.00 meal...");
System.out.println (" employee...");
employee.topUp(5.0);
buyAMeal (employee, 5.00);
System.out.println (" employee balance=" + employee.getBalance() + ", creditLimit=" + employee.getCreditLimit());
System.out.println (" employee2...");
employee2.topUp(5.0);
buyAMeal (employee2, 5.00);
System.out.println (" employee2 balance=" + employee2.getBalance() + ", creditLimit=" + employee2.getCreditLimit());
}
}
Sample output:
>>Creating employee ("CanteenAccount" and employee2 ("StaffAccount") objects...
>>Checking initial balances...
employee balance=2.0, creditLimit=5.0
employee2 balance=0.0, creditLimit=5.0
>>Buying a $5.00 meal...
employee...
ERROR:
-----------------------------
You must top-up your balance
Your new balance is: -3.0 GBP
You are: Using Credit
-----------------------------
employee balance=-3.0, creditLimit=5.0
employee2...
ERROR:
------------------------------
Cost exceeds the credit limit.
------------------------------
employee2 balance=0.0, creditLimit=5.0
>>Add $5.00 and buy another $5.00 meal...
employee...
ERROR:
-----------------------------
You must top-up your balance
Your new balance is: -3.0 GBP
You are: Using Credit
-----------------------------
employee balance=-3.0, creditLimit=5.0
employee2...
ERROR:
------------------------------
Cost exceeds the credit limit.
------------------------------
employee2 balance=5.0, creditLimit=5.0

Call Superclass method from overridden Subclass method

I'm sure this has a simple solution, but I'm new to Java and can't work it out.
I have a subclass Payroll that extends a superclass Pay, it contains an overridden method called 'calc_payroll'. From this method, I want to call the superclass method of the same name, and assign the output to a variable in the overriding method. My code is below
public class Payroll extends Pay
{
public double calc_Payroll()
{
double grossPay = super.calc_Payroll();
double taxAmt = tax(grossPay);
double netPay = grossPay - taxAmt;
System.out.println(grossPay);
return netPay;
}
}
Below is the code from the calc_payroll method in the superclass
public double calc_Payroll()
{
double otRate = rate * 1.77;
double otHours = ttlHours - stHours;
if(stHours == 0)
{
grossPay = otHours * rate;
}
else
{
grossPay = ((stHours * rate) + (otHours * otRate));
}
System.out.println(stHours + "//" + otHours + "//" + rate);//for testing
return grossPay;
}
the superclass method functions without issue to calculate and return the gross pay when called from a different subclass, but when calling it from a method with the same name, the print line in the code above (that I have labelled for testing) displays zero's for all variables
Code for full 'Pay' class is below as requested
public class Pay
{
private double ttlHours;
private int stHours;
private double rate;
double grossPay = 0.0;
final double TAXL = 0.07;
final double TAXM = 0.1;
final double TAXH = 0.16;
public void SetHours(double a)
{
ttlHours = a;
}
public void SetHoursStr(int a)
{
stHours = a;
}
public void SetRate(double a)
{
rate = a;
}
public double GetHours()
{
return ttlHours;
}
public int GetStHours()
{
return stHours;
}
public double GetRate()
{
return rate;
}
public double taxRate()
{
double taxRate = 0.0;
if(grossPay <= 399.99)
{
taxRate = TAXL;
}
else if(grossPay <= 899.99)
{
taxRate = TAXM;
}
else
{
taxRate = TAXH;
}
return taxRate;
}
public double tax(double grossPay)
{
double ttlTax = 0.0;
if(grossPay < 400.00)
{
ttlTax += (grossPay * TAXL);
}
else if(grossPay < 900.00)
{
ttlTax += (grossPay * TAXM);
}
else
{
ttlTax += (grossPay * TAXH);
}
return ttlTax;
}
public double calc_Payroll()
{
double otRate = rate * 1.77;
double otHours = ttlHours - stHours;
if(stHours == 0)
{
grossPay = otHours * rate;
}
else
{
grossPay = ((stHours * rate) + (otHours * otRate));
}
System.out.println(stHours + "//" + otHours + "//" + rate);//for testing
return grossPay;
}
}
The subclass Payroll contains no other code
Below is the code that accepts user input to assign values to the initialized variables
public class CalPayroll extends Pay
{
Payroll nPay = new Payroll();
Accept Read = new Accept();
public void AcceptPay()
{
char select = '0';
while(select != 'e' && select != 'E')
{
System.out.println("Payroll Computation \n");
System.out.print("Enter number of hours worked (00.0) <0 for Quick exit>: ");
SetHours(Read.AcceptInputDouble());
System.out.print("Enter first number of hours straight (integer or 0 to disable): ");
SetHoursStr(Read.AcceptInputInt());
System.out.print("Enter hourly rate of worker (00.00): ");
SetRate(Read.AcceptInputDouble());
Screen.ScrollScreen('=', 66, 1);
Screen.ScrollScreen(1);
displayInfo();
System.out.println("e to exit, any other letter + <Enter> to continue");
select = Read.AcceptInputChar();
}
}
public void displayInfo()
{
NumberFormat currency = NumberFormat.getCurrencyInstance();
NumberFormat percent = NumberFormat.getPercentInstance();
System.out.println("Gross pay is :" + currency.format(calc_Payroll()));
System.out.println("Tax is :" + percent.format(taxRate()));
System.out.println("Net pay is :" + currency.format(nPay.calc_Payroll()));
Screen.ScrollScreen(1);
}
}
I'm confused!
Its clear from you code that ttlHours, stHours and rate are not initialised with some reasonable value. So when you just call super.calc_Payroll(), values like 0 or 0.0 are used as i explained in my comment. Its good to first set values of these variables before calling super.calc_Payroll().
SetHours(23.4); //some value
SetHoursStr(5); //some value
SetRate(2.3); //some value
Also you don't have constructor for Pay class, try making it and initialising all uninitialised variable in constructor or use setter/getter methods to set and get values.
Since your both classes extends Pay class, it creates the problem which you are facing. When you call SetHours(Read.AcceptInputDouble()), it set the variable inherited by CalPayroll from Pay, not the variables inherited by Payroll class. What you have to do is to set variables for Payroll instance as well as for current class as both extends Pay. Do the following replace your while loop as,
while(select != 'e' && select != 'E')
{
System.out.println("Payroll Computation \n");
System.out.print("Enter number of hours worked (00.0) <0 for Quick exit>: ");
SetHours(Read.AcceptInputDouble());
nPay.SetHours(GetHours());
System.out.print("Enter first number of hours straight (integer or 0 to disable): ");
SetHoursStr(Read.AcceptInputInt());
nPay.SetHoursStr(GetStHours());
System.out.print("Enter hourly rate of worker (00.00): ");
SetRate(Read.AcceptInputDouble());
nPay.SetRate(GetRate());
Screen.ScrollScreen('=', 66, 1);
Screen.ScrollScreen(1);
displayInfo();
System.out.println("e to exit, any other letter + <Enter> to continue");
select = Read.AcceptInputChar();
}
Please post the complete code.
It seems that for some reason your variables of super class method not getting assigned values properly. And they are initialized with their default values which is making everything 0. I'll be able to help better if you paste the complete class.

How to store 2 variables and compare them

I am trying to accept user input for two people's hourly wage and the amount of hours of overtime they work per year.
using an algorithm I have researched, the program will tell both people the amount of money they make per year and the amount of taxes they pay, which is based on the amount that they make.
This is all fine and dandy. However, what I am now trying to do is to add a line at the end of the program which states who is paying more taxes. This would be accomplished with the method whoPaysMoreTaxes, but I have no idea what to include in that method. I know I would need a simple if/ else if/ else statement to get the job done, but I do not know how I would go about storing the taxes of person 1 and the taxes of person 2 and compare them. The output should be as follows I believe. The numbers 22, 100, 58, and 260 are user input:
Person 1's hourly wage: 22
Person 1's overtime hours for the year: 100
You will make $45540 this year
And you will pay $9108 in taxes
Person 2's hourly wage: 58
Person 2's overtime hours for the year: 260
You will make $133980 this year
And you will pay $40194 in taxes.
Person 2 is paying more taxes.
The issue I am having is finding a way to produce that final line that says who is paying more taxes.
public class conditionalsAndReturn
{
public static void main(String[] args)
{
Scanner console = new Scanner(System.in);
taxes(console, 1);
taxes(console, 2);
}
public static void taxes(Scanner console, int personNum)
{
System.out.print("Person " + personNum + "'s hourly wage: ");
int wage = console.nextInt();
System.out.print("Person " + personNum + "'s overtime hours for the year: ");
double totalOvertimeHours = console.nextInt();
int salary = annualSalary(wage, totalOvertimeHours);
System.out.println("You will make $" + salary + " this year");
System.out.println("And you will pay $" + taxation(salary) + " in taxes");
System.out.println();
}
public static int annualSalary(int wage, double totalOvertimeHours)
{
double workHoursPerWeek = 40 + totalOvertimeHours / 48;
return (int)(weeklyPay(wage, workHoursPerWeek) * 48);
}
public static double weeklyPay(int wage, double workHoursPerWeek)
{
if (workHoursPerWeek > 40)
{
return (wage * 40) + ((wage + wage / 2.0) * (workHoursPerWeek - 40));
}
else
{
return wage * workHoursPerWeek;
}
}
public static int taxation(int salary)
{
if (salary < 20000)
{
return 0;
}
else if (salary > 100000)
{
return salary * 3 / 10;
}
else
{
return salary * 2 / 10;
}
}
public static String whoPaysMoreTaxes(
}
The OOP conform coding would be, to have a class person (or better employee), with the fields: personNum, one or more of the three wage/salary variables, taxation. Add name and such if needed.
Now you can use instances of those class to store the accumulated data, and compare the objects with a compareTo.
If you were to follow true Object Oriented programming principles, then you might create a separate class which represents a Person object (or consider a nested class). Then each Person instance could have the attributes:
hourly_wage
overtime_hours
income
taxes_owed
You would then want to create as many People classes as you need, using the class instances to store data. You could then modify your method header to be:
public Person who_payes_more_taxes(Person p1, Person p2): { ... }
Inside the method you would need to decide how to compare taxes, but most likely it will look something like:
if (p1.taxes_owed > p2.taxes_owed) { return p1 }
You're definitely on the right track. I would use more variables to simplify comparing the taxes:
import java.util.Scanner;
public class ConditionalsAndReturn
{
public static void main(String[] args)
{
int personOneWage;
int personOneOvertime;
double personOnePayBeforeTax;
double personOneTaxes;
double personOneNetIncome;
int personTwoWage;
int personTwoOvertime;
double personTwoPayBeforeTax;
double personTwoTaxes;
double personTwoNetIncome;
Scanner scan = new Scanner(System.in);
System.out.print("Person 1's hourly wage: ");
personOneWage = scan.nextInt();
System.out.print("Person 1's overtime hours for the year: ");
personOneOvertime = scan.nextInt();
personOnePayBeforeTax = (40 * personOneWage) + (personOneOvertime * personOneWage * 1.5);
personOneTaxes = taxes(personOnePayBeforeTax);
personOneNetIncome = personOnePayBeforeTax - personOneTaxes;
System.out.println("You will make $" + personOneNetIncome + " this year");
System.out.println("And you will pay $" + personOneTaxes + " in taxes");
System.out.print("Person 2's hourly wage: ");
personTwoWage = scan.nextInt();
System.out.print("Person 2's overtime hours for the year: ");
personTwoOvertime = scan.nextInt();
personTwoPayBeforeTax = (40 * personTwoWage) + (personTwoOvertime * personTwoWage * 1.5);
personTwoTaxes = taxes(personTwoPayBeforeTax);
personTwoNetIncome = personTwoPayBeforeTax - personTwoTaxes;
System.out.println("You will make $" + personTwoNetIncome + " this year");
System.out.println("And you will pay $" + personTwoTaxes + " in taxes");
if (personOneTaxes > personTwoTaxes)
{
System.out.println("Person 1 is paying more in taxes.");
}
else
{
System.out.println("Person 2 is paying more in taxes.");
}
scan.close();
}
private static double taxes(double payBeforeTax)
{
if (payBeforeTax < 20000)
{
return 0;
}
else if (payBeforeTax > 100000)
{
return payBeforeTax * 3 / 10;
}
else
{
return payBeforeTax * 2 / 10;
}
}
}

Move a method to another method java

import java.util.Scanner;
public class Hw4Part4 {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
//Ask for the diners’ satisfaction level using these ratings: 1 = Totally satisfied, 2 = Satisfied,
//3 = Dissatisfied.
System.out.println("Satisfacion leve: ");
int satisfactionNumber= sc.nextInt();
//Ask for the bill subtotal (not including the tip)
System.out.println("What is the bill subtotal: ");
double subtotal= sc.nextInt();
//Report the satisfaction level and bill total.
System.out.println("The satisfaction level is: "+ satisfactionLevel(satisfactionNumber));
System.out.println("The bill total is: " + getBillTotal(tipPercentage, subtotal));
}
public static String satisfactionLevel(int satisfactionNumber){
String satisfactionL = "";
if (satisfactionNumber == 1){
satisfactionL ="Totally-satisfied";
}
if (satisfactionNumber == 2){
satisfactionL = "Satisfied";
}
if (satisfactionNumber == 3){
satisfactionL = "Dissatisfied";
}
return satisfactionL;
}
//This method takes the satisfaction number and returns the percentage of tip to be
//calculated based on the number.
//This method will return a value of 0.20, 0.15, or 0.10
public static double getPercentage(int satisfactionNumber){
double getPercentage = 0;
if (satisfactionNumber ==1){
getPercentage = 0.20;
}
if (satisfactionNumber ==2){
getPercentage = 0.15;
}
if (satisfactionNumber ==3){
getPercentage = 0.10;
}
return getPercentage;
}
public static double getBillTotal(double tipPercentage, double subtotal){
double totalWithTip= (subtotal + ( getPercentage(satisfactionNumber) * subtotal));
return totalWithTip;
}
}
I am having issues on the last method, the whole code is shown above.
It says there is error with the part where I am trying to use the previous method.
I need to get the percentage which was computed on the previous method.
At this part of the code:
public static double getBillTotal(double tipPercentage, double subtotal){
double totalWithTip= (subtotal + ( getPercentage(satisfactionNumber) * subtotal));
return totalWithTip;
}
You call this method:
getPercentage(satisfactionNumber)
However, this variable:
satisfactionNumber
Doesn't exist in this method's scope. You should pass this variable to the method as so:
public static double getBillTotal(double tipPercentage, double subtotal, int satisfactionNumber){
double totalWithTip= (subtotal + ( getPercentage(satisfactionNumber) * subtotal));
return totalWithTip;
}
So when you call the method in the main, you pass it in:
System.out.println("The bill total is: " + getBillTotal(tipPercentage, subtotal, satisfactionNumber));
tipPercentage cannot be resolved to a varible
Pretty much any variable you pass in, you must create. So when you do the above line, make sure you have all variables delcared:
double tipPercentage, subtotal, satisfactionNumber;
//now set these three variables with a value before passing it to the method
System.out.println("The bill total is: " + getBillTotal(tipPercentage, subtotal, satisfactionNumber));
It's hard to tell, but I think you need to remove whitespace:
double totalWithTip = subtotal + (getPercentage(satisfactionNumber) * subtotal);
return totalWithTip;
This code assumes a variable:
int satisfactionNumber;
and a method:
double getPercentage(int satisfactionNumber) {
// some impl
}

How to create an equals Method in Java for 2 credit cards

so I'm having an issue writing my code such that i will be able to create an equals method that will return true if 2 credit cards are equal if they have the same Security code, company and account number.
Heres my code so far.
public class CreditCard {
private double balance;
public static double interestRate;
public static String personname;
public static String company;
public static double creditLine;
public CreditCard ()
{
balance = 0;
}
public static void setIntRate (double rate)
{
interestRate = rate;
System.out.println("The Interest rate for this card is : " + interestRate);
}
public static double getIntRate ()
{
return interestRate;
}
public static void setPersonName (CreditCard card ,String pName)
{
personname = pName;
System.out.println("Name on card: " + personname);
}
public static void setCompany (CreditCard card, String compName)
{
company =compName;
System.out.println("The Company name is : "+ company);
}
//creates new card number
public static void CardNum (CreditCard card)
{
int[] accountnumber = new int [16];
Random generator = new Random ();
for (int i =0; i<16; i++)
accountnumber [i] = (int)(Math.random()*10);
System.out.println ("The Account number for this card is: " + (java.util.Arrays.toString(accountnumber))+"");
}
//Creates new securitycode
public static void getSecurityCode (CreditCard card)
{
int[] securitycode = new int [3];
Random generator = new Random ();
for (int i =0; i<3; i++)
securitycode [i] = (int)(Math.random()*10);
System.out.println ("The security code for this card is: " + (java.util.Arrays.toString(securitycode))+"");
}
public static void setexpirationdate(int MM, int YY)
{
System.out.println("The expiration date for this card is: " + MM + "/"+ YY + "\n");
}
public static void setCreditLine (int cLine){
creditLine =cLine;
}
public static void getCreditLine (CreditCard card)
{
System.out.println( " CreditLine is : $" + creditLine);
}
// buys something
public void buyWithCreditCard (double amount)
{
balance = balance + amount;
}
//Inserts money to reduce balance
public double paybalance (double amount)
{
if (balance >= amount){
balance = balance - amount;
roundBalance();}
else{
creditLine = creditLine + (amount - balance);
balance = 0;
System.out.println("Your new CreditLine is: "+creditLine);
roundBalance();
}
return amount;
}
// adds interest to balance
public void addInterest ()
{
double interest = balance * getIntRate ();
balance = balance + interest;
roundBalance ();
}
private void roundBalance ()
{
balance = (double)(Math.round(balance*100))/100;
}
public double checkBalance (){
return balance;
}
//Shows Credit Card Debt
public static void showBalance (CreditCard card)
{
System.out.print(card.balance);
}
}
and then the class that utilizes the CreditCard Class.
public class CreditCardDemo {
public static void main (String [] args)
{
//Creates cards 1 and 2
CreditCard firstCard = new CreditCard ();
CreditCard secondCard = new CreditCard ();
//Calls for card info 1
System.out.println("First card Information is:");
CreditCard.setPersonName(firstCard,"John White");
//CreditCard.getName(firstCard);
CreditCard.setCreditLine(600);
CreditCard.getCreditLine(firstCard);
CreditCard.setCompany(firstCard,"Visa");
CreditCard.setIntRate(0.02);
CreditCard.CardNum(firstCard);
CreditCard.getSecurityCode(firstCard);
CreditCard.setexpirationdate(11, 17);
//call for card info 2
System.out.println("Second card Information is:");
CreditCard.setPersonName(secondCard,"Jack Black");
CreditCard.setCreditLine(2600);
CreditCard.getCreditLine(secondCard);
//CreditCard.getName(secondCard);
CreditCard.setCompany(secondCard,"Discover");
CreditCard.setIntRate(0.02);
CreditCard.CardNum(secondCard);
CreditCard.getSecurityCode(secondCard);
CreditCard.setexpirationdate(10, 19);
//Purchases
System.out.println("\nYou bought something for $5.00");
firstCard.buyWithCreditCard (5.00);
System.out.println("You bought another item for $12.00");
firstCard.buyWithCreditCard(12.00);
System.out.println("You bought another item for $15.00");
firstCard.buyWithCreditCard(15.00);
System.out.println("You bought another item for $33.42");
firstCard.buyWithCreditCard(33.42);
//Display Current Balance
System.out.print("You currently owe: $");
CreditCard.showBalance(firstCard);
//Interest Adds onto it
if (firstCard.checkBalance () > 50.00){
System.out.println("\nInterest has been added");
firstCard.addInterest ();
System.out.print("Your new balance is : $");
CreditCard.showBalance(firstCard);
System.out.println("");
//Payment
System.out.println("You have overpaid your balance.");
firstCard.paybalance (70);
System.out.print("Your new balance is : $");
CreditCard.showBalance(firstCard);
}
}
}
So if anyone could show me how to create a method in the CreditCard class that would allow me to check if the firstCard and secondCard, that would be great. Thanks a bunch :)
If you use NetBeans, you can simply auto-generate the equals function (not sure about Eclipse). Other than that it boils down to overwriting the equals function of Object.
Make sure to check that both are of the same class and make sure to check for null. Java recommends to as well overwrite the hashCode function, however that depends on your use-case.
first of all, i'm not that advanced in java, but this seems simple enough still.
The problem here seems that the security code is never saved (the method getSecurityCode is void and all variables are only local)
Same goes for the company
nonetheless, here's an example, assuming you fixed that and made a method getCode that returns the code (as int) and a method getAccountNumber, that returns that number (as int). (and assuming it's no problem to make those methods public)
public boolean equals(CreditCard creditCard1, CreditCard creditCard2){
if (creditCard1 == null || creditCard2 == null)
return creditCard1 == creditCard2;
boolean equalCode = (creditCard1.getCode() == creditCard2.getCode());
boolean equalCompany = creditCard1.company.equals(creditCard2.company);
boolean equalAccountNumber = (creditCard1.getAccountNumber() == creditCard2.getAccountNumber());
return equalCode && equalCompany && equalAccountNumber;
}
It would be good practice to make the variables private and make some getters, but that's up to you.

Categories

Resources