Problems using constructors and getting methods for another class - java

So i keep getting errors when i try to run the user class saying double is required an no arguments are found. I'm getting errors on lines 17, 40, 42, 44, 46 and 48. They're all errors which say doubles are required. Answers in plain English would be appreciated.
My main class:
import java.util.Scanner;
public class ElectricityCalculatorUser {
//Main method
public static void main (String [] args) {
ElectricityCalculator myCalculator = new ElectricityCalculator();
Scanner input = new Scanner (System.in);
//Input the initial reading
double initialReading;
System.out.print ("What is the inital reading on your electricity meter in kwH? ");
initialReading = input.nextDouble ();
//Input the final reading
double finalReading;
System.out.print ("What is the final reading on your electricity meter in kwH? ");
finalReading = input.nextDouble ();
//Input the number of days
//between readings
double numberOfDays;
System.out.print ("How many days have passed between your initial and final reading? ");
numberOfDays = input.nextDouble ();
//Calculations
double totalElectricityUsed = myCalculator.totalElectricityUsed();
System.out.print ("Total electricity used = " + totalElectricityUsed);
double costOfElectricity = myCalculator.costOfElectricity();
System.out.print ("Cost of electricity = " + costOfElectricity);
double standingCharge = myCalculator.standingCharge();
System.out.print ("Standing charge = " + standingCharge);
double costBeforeVAT = myCalculator.costBeforeVAT();
System.out.print ("Cost before VAT is added = " + costBeforeVAT);
double VAT = myCalculator.VAT();
System.out.print ("Cost of VAT = " + VAT);
double totalCost = myCalculator.totalCost();
System.out.print ("Total cost = " + totalCost);
}
}
My class with all the methods:
public class ElectricityCalculator {
//Attributes
private double initialReading;
private double finalReading;
private double numberOfDays;
//Constructors
public ElectricityCalculator (double ir, double fr, double nod) {
initialReading = ir;
finalReading = fr;
numberOfDays = nod;
}
//Calculating total electricity used
public double totalElectricityUsed () {
return finalReading - initialReading;
}
//Calculating cost of electricity
public double costOfElectricity () {
return totalElectricityUsed * 0.175;
}
//Calculating standing charge
public double standingCharge (double numberOfDays) {
return numberOfDays * 0.25;
}
//Calculating cost before VAT is added
public double costBeforeVAT (double costOfElectricity, double standingCharge) {
return costOfElectricity + standingCharge;
}
//Cost of VAT
public double VAT (double costBeforeVAT) {
return costBeforeVAT * 0.05;
}
//Total cost of electricity used
//including VAT
public double totalCost (double costBeforeVAT, double VAT) {
return costBeforeVAT + VAT;
}
}

In java, if you don't write a constructor, a default constructor will be added automatically for you, and this constructor would be public and takes no argument.
Something like the following:
public ElectricityCalculator () {
}
However, when you define any constructors, the default constructor will be removed. And hence, the only constructor that you have in your class is
public ElectricityCalculator (double ir, double fr, double nod) {
initialReading = ir;
finalReading = fr;
numberOfDays = nod;
}
And therefore
ElectricityCalculator myCalculator = new ElectricityCalculator();
Doesn't match any constructors.
you can simply create the instance after getting the values required to construct the object
ElectricityCalculator myCalculator = new ElectricityCalculator(initialReading, finalReading, numberOfDays);

In addition to Sleiman Jneidi answer, you are calling functions, but dont provide any parameters, as the method definition demands:
double standingCharge = myCalculator.standingCharge();
need to be changed to:
double standingCharge = myCalculator.standingCharge(10.0); //example for 10 days
same problem in the lines 42, 44, 46, 48 of your code

public ElectricityCalculator (double ir, double fr, double nod);
public double standingCharge (double numberOfDays);
public double costBeforeVAT (double costOfElectricity, double standingCharge);
public double VAT (double costBeforeVAT);
public double totalCost (double costBeforeVAT, double VAT);
The constructor and these methods take arguments but you are trying to call them as if they did not.
For the constructor, you can simply move this line
ElectricityCalculator myCalculator = new ElectricityCalculator();
to after you take input from the user so you can pass in the arguments.
// pass arguments here
// v v v
... = new ElectricityCalculator( initialReading , finalReading , numberOfDays );
For the other methods you need to be passing in the results of interim calculations. For example VAT(...) takes a costBeforeVAT which I assume should be the return value of costBeforeVAT(... , ...).
double costBeforeVAT = ...;
// pass argument here
// v
double VAT = myCalculator.VAT( costBeforeVAT );
Note that in some cases you probably do not need these methods to have certain parameters, for example
public double standingCharge () {
return numberOfDays * 0.25;
}
because numberOfDays was already a member of the class ElectricityCalculator and
public double costBeforeVAT () {
return costOfElectricity() + standingCharge();
}
because these methods can be called directly instead of asking for their results to be passed in.
Related: "Passing Information to a Method or a Constructor".

Related

Returning a value from one method to another to be used in the output

I can't figure out how to return the value of finalCost to the main method and have it printed.
import java.util.*;
public class PhonePlan {
private static double basecost = 8.5;
private static double rate = 0.35;
private static double discount = 0.15;
public static void main(String[] args) {
//Scan input for downloadLimit
Scanner scan = new Scanner(System.in);
System.out.print("Enter the download limit in GB: ");
int downloadLimit = scan.nextInt();
// Call other method
calcMonthlyCharge(downloadLimit);
System.out.println("Plan monthly cost: " + calcMonthlyCharge(finalCost));
}
public static double calcMonthlyCharge(double downloadLimit) {
// Calculate final cost
double fullCost = downloadLimit * rate + basecost;
double planDiscount = fullCost * discount;
double finalCost = fullCost - planDiscount;
return finalCost;
}
}
Specifically, I can't find how to use the returned value in the "println" line.
System.out.println("Plan monthly cost: " + calcMonthlyCharge(finalCost) );
}
public static double calcMonthlyCharge(double downloadLimit) {
// Calculate final cost
double fullCost = downloadLimit * rate + basecost;
double planDiscount = fullCost * discount;
double finalCost = fullCost - planDiscount;
return finalCost;
}
You call calcMonthlyCharge(downloadLimit),but don't store the returnvalue.
When you call System.out.println("Plan monthly cost: " + calcMonthlyCharge(finalCost) );
It is unknown what finalcost is, this is a variable which only exist in the scope of calcMonthlyCharge
Either store the returnvalue of calcMonthlyCharge(downloadLimit) and reuse the value to print, or use calcMonthlyCharge(downloadLimit) in your println with downloadLimit as parameter to get a new returnvalue.

Java inheritance: Why this program gives 0.0 in output

I have written this code. The output should calculate the interest of the Bank but it gives 0.0 as output. I have created a class named as Bank and extended it in ICICI class.
import java.util.Scanner;
public class Bank
{
static double rate;
// n = number of years
public double calculateInterest( double PrincipalAmount, double n)
{
double interest;
interest = (PrincipalAmount * n*rate) /100; // interest formula
return interest;
}
public static void main(String[] args)
{
Scanner s1 = new Scanner(System.in);
System.out.print("Enter PrincipalAmount :" );
double PrincipalAmount = s1.nextDouble();
Scanner s2 = new Scanner(System.in);
System.out.print("Enter Number of Years :" );
double n = s2.nextDouble();
ICICI ic;
ic = new ICICI();// new object created of ICICI Class
ic.rate = rate; // object call by reference
System.out.print("Interest of ICICI is " + ic.calculateInterest( PrincipalAmount,n));
}
}
public class ICICI extends Bank
{
double rate = 4;
}
you are doing following:
ic.rate = rate;
and rate is not initialized....
so ic.rate = 0.0;
you should by the way take a look at this:
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
What does the 'static' keyword do in a class?
and this
http://www.oracle.com/technetwork/java/codeconventions-135099.html
calculateInterest method is using static rate variable not instance rate , inheritance does not apply on variable , it does not override variable. so default value of static rate will be 0.0 and hence calculateInterest will give 0.0 (because it is double)answer.
You have mistakenly altered the assignment statement:
ic.rate = rate;
Instead, it should be :
rate= ic.rate;
Thanks!

Local variable undefined in my main

I'm in my intro to Java class and working on loops this week. I think I have the loop built but my variable within my main CommissionNotifications is undefined.
I think I have to create an object and reference the variable stored in my other class...am I on the right track?
The program asks for annual sales and then calculates there commission payment based upon the bracket they fall into. The commission payment is done through a If statement on the class and then the program displays what they could earn if they increased there sales by 5,000 up to 1.5 * of there sales. IE if they earn 100000 in sales the table should display there initial commission and then what they could earn if they increased there sales to 150000(1.5*)
Here is my class:
public class Calculations {
double TotalSales;
double ComRate = 0.025;
double AnnualSal = 80000;
double compensation;
double SalesTarget;
double Acceleration = 1.5;
double chart;
double ComAccFactor;
public double getCommissionNotifications() {
return CommissionNotifications;
}
public void setCommissionNotifications(double commissionNotifications) {
CommissionNotifications = commissionNotifications;
}
public double CommissionNotifications; {
if (TotalSales > 120000){
CommissionNotifications = AnnualSal + (TotalSales * (ComRate + Acceleration));
} else if (TotalSales > SalesTarget * .8) {
CommissionNotifications = AnnualSal + (TotalSales * ComRate);
} else {;
CommissionNotifications = AnnualSal;
}
}
}
Here is my Main
import java.util.*;
import java.text.*;
public class Paycheck {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner (System.in);
NumberFormat nf = NumberFormat.getCurrencyInstance();
System.out.println("Enter Total Commission Sales: ");
double TotalSales = input.nextDouble();
double Base = TotalSales;
double finish = TotalSales * 1.5;
System.out.println("Your Total compensation with your annual sales is: " + getCommissionNotifications);
int i = Base + 5000;
while (i <= finish) {
System.out.println(Base);
TotalSales += 5000;
}
}
}
getCommisionNotifications is a member of class Calculations. To access it you will need to create a new Calculations object:
Calculations c = new Calculations();
c.getCommisionNotifications();
This code looks a lot like C# with the capitalized variable names. Anyways, your
getCommissionNotifications method should handle the logic of what to return based on TotalSales. It's also not clear why you need a setter method, so I've commented that out.
As for using the below class, you need an instance of the Calculations class
Calculations calc = new Calculations();
double TotalSales = input.nextDouble();
calc.TotalSales = TotalSales;
// double Base = TotalSales; // Duplicate variable not needed
double finish = TotalSales * 1.5;
System.out.println("Your Total compensation with your annual sales is: " + calc.getCommissionNotifications());
public class Calculations {
double TotalSales;
double ComRate = 0.025;
double AnnualSal = 80000;
double compensation;
double SalesTarget;
double Acceleration = 1.5;
double chart;
double ComAccFactor;
public double getCommissionNotifications() {
if (TotalSales > 120000){
return AnnualSal + (TotalSales * (ComRate + Acceleration));
} else if (TotalSales > SalesTarget * .8) {
return AnnualSal + (TotalSales * ComRate);
} else {
return AnnualSal;
}
}
// Not sure why this is needed... You have a dynamic getter method
//public void setCommissionNotifications(double commissionNotifications) {
// CommissionNotifications = commissionNotifications;
//}
}

How do I use the return value from a method in another method different from the calling method?

I'm kinda new to to java and stumbled on a problem that needs me to do currency conversion declaring different methods for:
getting amount, getting conversion rate, doing the actual conversion and printing the outcome of the conversion
import java.util.*;
public class Conver {
public static void main(String[] args){
amountToConvert();
exchangeRate();
convert();
}
public static double amountToConvert() {
Scanner input = new Scanner(System.in);
System.out.println("Enter the amount you wish to convert...");
double amount = input.nextDouble();
return amount;
}
public static double exchangeRate(){
Scanner input = new Scanner(System.in);
System.out.println("Enter the currency you wish to convert from... ");
String initialCurrency = input.next();
System.out.println("Enter the currency you wish to convert from... ");
String finalCurrency = input.next();
System.out.println("How many " + initialCurrency + " makes one " + finalCurrency + "?");
double rate = input.nextDouble();
return rate;
}
public static double convert(){
int x = amount*rate;
return x;
}
public void printResult(){
System.out.println(x);
}
}
Learn to use parameters in the methods. Change the convert() method so that it looks like this:
public static double convert(double amount, double rate){
int x = amount*rate;
return x;
}
In the method above, double amount and double rate are the parameters. Use variables to help pass in parameters to convert() in the main method:
public static void main(String[] args){
double amount1 = amountToConvert();
double rate1 = exchangeRate();
double result = convert(amount1, rate1);
printResult(result);
}
Hope this helps!
Pass returned values to the method convert:
import java.util.*;
public class Conver {
public static void main(String[] args){
double amount = amountToConvert();
double rate = exchangeRate();
double result = convert(amount, rate);
printResult(result);
}
public static double amountToConvert() {
Scanner input = new Scanner(System.in);
System.out.println("Enter the amount you wish to convert...");
double amount = input.nextDouble();
return amount;
}
public static double exchangeRate(){
Scanner input = new Scanner(System.in);
System.out.println("Enter the currency you wish to convert from... ");
String initialCurrency = input.next();
System.out.println("Enter the currency you wish to convert from... ");
String finalCurrency = input.next();
System.out.println("How many " + initialCurrency + " makes one " + finalCurrency + "?");
double rate = input.nextDouble();
return rate;
}
public static double convert(double amount, double rate){
double x = amount * rate;
return x;
}
public void printResult(double x){
System.out.println(x);
}
}
Also, don't use double for money!
First off, you need to change the "receiving method" so that it takes an argument. A method like:
public static double convert() {}
that needs to take in a value for amount and rate, needs to have those added to the method signature:
public static double convert (double amount, double rate) {}
Putting the two comma separated values inside of the parens means that this method takes two values, doubles, as arguments. This makes those values available to use inside of that method.
Now that you have a method that can take the required arguments, you need to actually use that method in your code. When calling this method, you start out the same as with others:
convert(
but then you need to add in the arguments you are using:
double amount = amountToConvert();
double rate = exchangeRate();
convert(rate, amount);
If you want to avoid creating those two additional variables in main(), you can actually call those methods inside of your new method:
convert(amountToConvert(), exchangeRate());

Calling results from methods outside main into variables in the main method

My homework is to calculate taxes and surcharges for a jewelry store that is replenishing its stock, and I have run into a slight snag. I am using a method called calcExtraTax three times to calculate the labor rate and state and federal taxes. I then need to take the results of each instance of that method and pass the value into the appropriate variable in my main method. This is what my code looks like right now (evidently not complete):
import java.text.DecimalFormat;
import java.util.Scanner;
import javax.swing.JOptionPane;
public static void main(String[] args)
{
double stateRate = 0.1;
double luxuryRate = 0.2;
double laborRate = 0.05;
double extraCharge;
int numOrdered;
double diamondCost;
double settingCost;
double baseCost;
double totalCost;
double laborCost;
double stateTax;
double luxuryTax;
double finalAmountDue;
Scanner keyInput = new Scanner(System.in);
System.out.println("What is the cost of the diamond?");
diamondCost = keyInput.nextDouble();
System.out.println("What is the cost of the setting?");
settingCost = keyInput.nextDouble();
System.out.println("How many rings are you ordering?");
numOrdered = keyInput.nextInt();
baseCost = diamondCost + settingCost;
calcExtraCost(baseCost, laborRate);
laborCost = extraCharge;
calcExtraCost(baseCost, stateRate);
stateTax = extraCharge;
calcExtraCost(baseCost, luxuryRate);
luxuryTax = extraCharge;
totalCost = baseCost + laborCost + stateTax + luxuryTax;
finalAmountDue = numOrdered*totalCost;
JOptionPane.showMessageDialog(null, "The final amount due is = " + finalAmountDue);
}
public static void calcExtraCost(double diamond, double rate)
{
double extraCharge = diamond*rate;
???????????
}
what i'm trying to figure out is what else i need to put in my secondary method in order to be able to pass the result into a different tax cost variable each time depending on the rate variable used in the formula.
You don't need to do anything special with your calcExtraCost apart from changing the return type to double and returning the calculated value. For example
public static double calcExtraCost(double diamond, double rate)
{
double extraCharge = diamond*rate;
double tax = //some calculations
return tax
}
So this method would return the calculated value.
In your main method you need to store that value to the appropriate double that you want. For example if you want to calculate the luxuryTax, then you do something like:
luxuryTax = calcExtraCost(baseCost, luxuryRate);
Also some advice, instead of making your method static, make it a non-static method, and create an object of the class where your method is defined, and call the method on that object.
For example if the class where you defined your method is called Tax, then you create an object of Tax:
Tax tax = new Tax();
and call calcExtraCost on that object:
tax.calcExtraCost();
This way you remove the static part of the method. So your method signature becomes like this:
public double calcExtraCost(double diamond, double rate)
You can return the value of diamond*rate from your helper method by changing its signature from void to double and adding a return statement:
public static double calcExtraCost(double diamond, double rate)
{
return diamond * rate;
}
Now you can assign the result of a call to the variable in your main method:
laborCost = calcExtraCost(baseCost, laborRate);

Categories