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);
Related
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!
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());
So I have to make a program in class and i'm having some trouble.
I have to call the examAverage method, which has parameters and i'm not sure how to. Also, in the user prompts method, I have to make a loop in main that call user prompts method and ask the user to input their exam score 3 times to get the average. I hope I explained it well. Im not very good at programming.
package project5;
import java.util.*;
public class Project5 {
static final int NUM_EXAMS = 3;
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
//declare variable
double Average;
double examScore1 = 0;
double examScore2 = 0;
double examScore3 = 0;
double Average = examAverage(examScore1, examScore2, examScore3) / NUM_EXAMS;
printWelcome();
userPrompts();
display();
}
static void printWelcome() {
System.out.println("Welcome to the Exam Average Calculator");
}
public static void userPrompts() {
System.out.println("Please enter your 1st exam score.");
double examScore1;
examScore1 = console.nextDouble();
System.out.println("Please enter your 2nd exam score.");
double examScore2;
examScore2 = console.nextDouble();
System.out.println("Please enter your 3rd exam score.");
double examScore3;
examScore3 = console.nextDouble();
}
public static void display() {
double examAverage = 0;
}
public static double examAverage(double examScore1, double examScore2, double examScore3, double sum, double NUM_EXAMS) {
double Average;
sum = examScore1 + examScore2 + examScore3;
Average = (double) sum / NUM_EXAMS;
return Average;
}
public static void displayAverage(double Average) {
Object[] examAverage = null;
System.out.println("Your exam average is %.2f%", examAverage);
}
public static double examAverage(double examScore1, double examScore2, double examScore3) {
double Average;
{
return double Average
I don't want to do your homework for you but you call a method with paramaters severals times in your code. For example inside your main:
examAverage(examScore1, examScore2, examScore3)
you call the examAverage method passing in 3 variables. Your three variables are all set to 0, so that makes no sense. you probably should call your userPrompts before you call your examAverageMethod to initialize your examscores.
your program looks like it's almost done, think about the order of how you want to do it. good luck
So your exam average function is all messed up, what you want is it to take number of exams and the individual values and return the average.
So you make the function like this because you don't need to have sum as a parameter.
public static double examAverage(double examScore1, double examScore2, double examScore3, double NUM_EXAMS) {
double Average;
double sum = examScore1 + examScore2 + examScore3;
Average = sum / NUM_EXAMS;
return Average;
}
So when you call this function, you need to give it 4 values
so call it like this
double Average = examAverage(examScore1, examScore2, examScore3, 3);
That should solve your issue with the function. Let me know if I didn't explain it clearly enough or if you want me to elaborate.
You also have an issue on what order you call your code.
First, you want to welcome the user, then you want to ask them for their values, then you want to use those values to calculate the average and then you want to print that average so do this instead.
//declare variable
double Average;
double examScore1 = 0;
double examScore2 = 0;
double examScore3 = 0;
//Welcomes user, then prompts for exam values, calculates average using those values, and finally displays the average
printWelcome();
userPrompts();
double Average = examAverage(examScore1, examScore2, examScore3, 3);
System.out.println("your average is" + Average)
Also, delete your Display() and DisplayAverage() functions, they are useless.
On way would be to call your variables static by defining at class level like:
private static double examScore1 = 0;
private static double examScore2 = 0;
private static double examScore3 = 0;
Other best way would be to wrap all these variables in a class (or better create a list/array) and pass that call in userPrompts method and populate it and then using same object you calculate average.
Regarding looping, here's how you could do it:
create a counter and initialize it with 0.
while count <= 3
do
ask input from user
calculate average
display the average
done
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".
The problem is the following:
(Savings Account Class) Create class SavingsAccount. Use a static
variable annualInterestRate to store the annual interest rate for all
account holders. Each object of the class contains a private instance
variable savingsBalance indicating the amount the saver currently has
on deposit. Provide method calculateMonthlyInterest to calculate the
monthly interest by multiplying the savingsBalance by
annualInterestRate divided by 12—this interest should be added to
savings- Balance. Provide a static method modifyInterestRate that sets
the annualInterestRate to a new value. Write a program to test class
SavingsAccount. Instantiate two savingsAccount objects, saver1 and
saver2, with balances of $2000.00 and $3000.00, respectively. Set
annualInterestRate to 4%, then calculate the monthly interest for each
of 12 months and print the new balances for both savers. Next, set the
annualInterestRate to 5%, calculate the next month’s interest and
print the new balances for both savers.
I solved it all, but the balance is not incrementing -- it is staying the same. It should increment with every change in annual interest rate (at least, that's what I understood).
class SavingsAccount
{
static double annualInterestRate;
private double savingsBalance;
public SavingsAccount(double balance)
{
savingsBalance = balance;
}
public double calculateMonthlyInterest()
{
return (savingsBalance*annualInterestRate)/12;
}
public static void modifyInterestRate(double rate)
{
annualInterestRate = rate;
}
public static double getannualInterestRate(){return annualInterestRate;}
public double getsavingsBalance(){return savingsBalance;}
}
public class SavingsTest
{
public static void main(String args[])
{
SavingsAccount saver1 = new SavingsAccount(2000.0);
SavingsAccount saver2 = new SavingsAccount(3000.0);
SavingsAccount.modifyInterestRate(4);
System.out.printf("Balance for Saver1 = %.2f\nBalance for Saver2 = %.2f\nInterest Rate = %.2f\n\n",saver1.getsavingsBalance()+saver1.calculateMonthlyInterest(),saver2.getsavingsBalance(),SavingsAccount.getannualInterestRate());
SavingsAccount.modifyInterestRate(5);
System.out.printf("New Balance for Saver1 = %.2f\nNew Balance for Saver2 = %.2f\nInterest Rate = %.2f\n\n",saver1.getsavingsBalance(),saver2.getsavingsBalance(),SavingsAccount.getannualInterestRate());
}
}
You are not modifying the value of savingsBalance in this code.
public double addMonthlyInterest() {
savingsBalance += (savingsBalance*annualInterestRate)/12;
return savingBalance;
}
This will return the new balance and 'increment'
In your first print statement, for the first argument you are calculating the balance after calculating the monthly interest and adding them together and didn't set the new value as the value of the class member savingsBalance.
In your second print statement, since you did not set the calculated value back to the class member through a setter, it is simply printing out the original value that the classes were instantiated with.
On a side note, don't do inline calculations in print statements. They are confusing and not easy to read for anyone. A good way is to initialize local members in the method and using them for calculations and printing the local members.
Just wanted to share my answer.
public class SavingsAccount {
private static float annualInterestRate = 0f;
private float savingsBalance;
public SavingsAccount(float balance) {
savingsBalance = balance;
}
public static void setAnnualInterestRate(float t) {
if (t >= 0 && t <= 1)
annualInterestRate = t;
else
throw new IllegalArgumentException("Annual interest rate should be between 0 and 1");
}
private float calculateMonthlyInterest() {
return savingsBalance * annualInterestRate / 12;
}
public float getSavingsBalance() {
return savingsBalance + calculateMonthlyInterest();
}
public float getAnnualInterestRate(){
return annualInterestRate;
}
public String toString() {
return String.format("Balance: %.2f", getSavingsBalance());
}
}
in main
SavingsAccount s1 = new SavingsAccount(2000);
SavingsAccount s2 = new SavingsAccount(3000);
SavingsAccount.setAnnualInterestRate(0.04f);
System.out.println("S1: " + s1);
System.out.println("S2: " + s2);
SavingsAccount.setAnnualInterestRate(0.05f);
System.out.println("S1: " + s1);
System.out.println("S2: " + s2);