Java Else without IF error while calculating sales amount - java

I am getting else without If error while trying to compute the following:
You have just started a sales job in a department store. Your pay consists of a base salary and a commission. The base salary is 5,000. The scheme shown below is used to determine the commission rate.
Sales Amount Commission Rate
0.01–5,000 8 percent
5,000.01–10,000 10 percent
10,000.01 and above 12 percent
Your goal is to earn 30,000 a year. Write a program that finds out the minimum number of sales you have to generate in order to make 30,000.
Although I am not yet sure if my algorithm is right too, since I need to resolve the error first. Thank you.
import java.util.Scanner;
public class Commissionsales {
public static void main(String[] args) {
// create scanner
Scanner s = new Scanner(System.in);
double saleAmount = s.nextDouble();
double salary = 5000;
int target = 30000;
int sale = 0;
while (salary<=target){
if(saleAmount<5000){
double commissionrate = 0.08;
double commission = commissionrate*saleAmount;
salary+=commission;
sale++;
}
System.out.println("The minimum sales needed to earn 30,000:"+ sale);
break;
else if ((5000<saleAmount) && (saleAmount<10000))
{
double commissionrate = 0.10;
double commission = commissionrate*saleAmount;
salary+=commission;
sale++;
}
System.out.println("The minimum sales needed to earn 30,000:"+ sale);
break;
else if (saleAmount>10000){
double commissionrate = 0.12;
double commission =commissionrate*saleAmount;
salary+=commission;
sale++;
}
break;
}
System.out.println("The minimum sales needed to earn 30,000:"+ sale);
}
}

You can not have System.out.println this way:
...
}
System.out.println("The minimum sales needed to earn 30,000:"+ sale);
break;
else if ((5000<saleAmount) && (saleAmount<10000))
{
....
After closing ifblock, you need to write else if immediately, or error happens.

Related

Compounding interest calculator

My goal is to create a program that asks the user for an amount, asks for the interest rate per year, month or day, asks for how it will be compounded, then asks for the term in either months, days or years.
It ill then print the future value along with the total interest gained.
This is what I have so far and the numbers are incorrect.
if anyone could help revise this and make it work i would be very grateful.
import java.util.Scanner;
public class Compunding {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double compoundingTerms;
double period = 0;
System.out.println("Enter an amount of money: ");
double amount = sc.nextDouble();
System.out.println("Enter an rate of Interest: ");
double rate = sc.nextDouble();
System.out.println("Enter per years, months, or days: ");
String time = sc.next();
System.out.println("Enter how it will be componded monthly, semi-anually, quarterlly, anually: ");
String compoundRate = sc.next();
System.out.println("Enter the term amount: ");
double term = sc.nextDouble();
System.out.println("Enter the term type (Monthy,Yearly,Daily}: ");
String termType = sc.next();
if (time.equals("years")) {
period = 1;
}
if (time.equals("months")) {
period = 12;
}
if (time.equals("days")) {
period = 365;
}
if (compoundRate.equals("monthly")) {
rate = (rate / 100) / 12;
term = term * 12;
}
if (compoundRate.equals("semi-anually")) {
rate = (rate / 100) / 2;
term = term * 2;
}
if (compoundRate.equals("quarterlly")) {
rate = (rate / 100) / 4;
term = term * 4;
}
if (compoundRate.equals("anually")) {
rate = rate / 100;
term = term * 1;
}
double compoundPayment = 0;
for (int i = 1; i <= term; i++ ) {
if (i % period == 0 ) {
colInterest(amount, rate);
}
compoundPayment = amount * (1.0 + rate);
}
System.out.println("The Final payment will be: " + compoundPayment);
}
public static double colInterest(double valueAmount, double valueInterest) {
return valueAmount * valueInterest;
}
}
So there were a number of issues with the original calculation and what was posted. compoundPayment was set outside the for loop, and only once, so that compounding did not occur. Also, the term type was requested but not used, so every term was assumed to be years. I think it's also just hard to follow the logic of the for loop with the mod (I get it, that when we hit a day on which things are compounded, we give interest), but it's tricky to keep track of the various units (so I went for years, but one could make a case for days and a loop like yours). I did simplify and assume the rate given was annual, but you could make it daily and multiply by 365, or monthly and multiply by 12, or, just make sure your period and days have the same unit.
It's also the case that the choice of Double as opposed to BigDecimal to represent the money is one where I followed you lead and am answering the question asked. I'm not arguing what I'm answering here is the best possible approach (and one could enhance by using Currency as opposed to assuming it's in dollars).
One different approach would be to use exponents to work with repeated multiplications, or, even if not, to simplify the for loop (which allows you to do things like print statements along the way and allow for rounding of currency).
I am not fixing potential enhancements like that there aren't always 365 days in a year or formatting the decimals nicely or checking input more vigorously. I am trying to give a sense of a possible way to go.
One subtlety is the cast to (int) for numPeriods, which will, assuming the other parts worked (and I tested that 364 days compounded annually gave no interest, but 365 did), make sure not to give partial interest for periods not completed.
I hope that helps.
import java.util.Scanner;
public class Compounding {
private Scanner sc;
Compounding() {
sc = new Scanner(System.in);
}
public double getAmount() {
//enhancement: catch number format exceptions, negative numbers, etcetera, and presumbaly use a loop to retry
System.out.println("Enter an amount of money: ");
return sc.nextDouble();
}
//return interest as a rate
public double getInterestRate() {
//enhancement, validate input, catch errors
System.out.println("Enter an annual percent rate of interest: ");
double rate = sc.nextDouble();
return rate / 100;
}
public int getTimesCompoundedPerYear() {
System.out.println("Enter how it will be componded monthly, semi-anually, quarterly, anually: ");
String compoundRate = sc.next();
if (compoundRate.equals("monthly")) {
return 12;
} else if (compoundRate.equals("semi-anually")) {
return 2;
} else if (compoundRate.equals("quarterly")) {
return 4;
} else if (compoundRate.equals("annually")) {
return 1;
} else {
System.out.println("Unrecognized compounding, defaulting to monthly");
return 12;
}
}
//return term amount, units still tbd
//allowing for decimals in case someone says 6.5 years for dsomey=thing compounded more than once a year
public double getTermAmount() {
//enhancement, validate input, catch errors
System.out.println("Enter term amount: ");
return sc.nextDouble();
}
public String getTermUnits() {
System.out.println("Enter the term type (years, months, days): ");
String termType = sc.next();
if (termType.equals("years") || termType.equals("months") || termType.equals("days")) {
return termType;
} else {
System.out.println("Unrecognized time period, defaulting to years.");
return "years";
}
}
public static void main(String[] args) {
Compounding compounding = new Compounding();
double period = 12;
double amount = compounding.getAmount();
double annualRate = compounding.getInterestRate(); //interest rates are always quoted as annual, no need to vary that
int timesCompoundedPerYear = compounding.getTimesCompoundedPerYear();
double term = compounding.getTermAmount();
String termUnits = compounding.getTermUnits();
double ratePerPeriod = annualRate / timesCompoundedPerYear;
double timeInYears = term;
if (termUnits.equals("months")) {
timeInYears /= 12;
} else if (termUnits.equals("days")) {
timeInYears /= 365;
}
int numPeriods = (int) timeInYears * timesCompoundedPerYear;
double compoundPayment = amount * Math.pow(1 + ratePerPeriod, numPeriods);
System.out.println("The Final payment will be: " + compoundPayment);
}
}

Access Method result in If statement

Is it possible to access the result of a method statement in an If statement? I'm writing a program to calculate a meter reading assignment. Netbeans states it cannot find the symbol of the methodName I created. Here is the code so far:
public class Meter_Utility {
//Begin Main Method
public static void main(String[] args) {
//new scanner object
Scanner input = new Scanner(System.in);//create new scanner object
//Declarations
double prevMeter;
double currMeter;
double rate = 0;
// double totalUsage = 0;
//obtain meter readings from user
System.out.print("Welcome to the City Power Bill Calculator! Please enter your previous meter reading: ");
prevMeter = input.nextDouble();
System.out.print("Please enter your Current meter reading: ");
currMeter = input.nextDouble();
//output total usage
System.out.printf("your usage was: %.1f KwHs", totalUsage(prevMeter, currMeter));
//calculate rate
if (totalUsage < 500) {
rate = .0809;
}
else if (totalUsage > 500 && totalUsage < 900){
rate = .091;
}
else {
rate = .091;
}
//output rate
System.out.printf("\nYour rate was: %.4f/KwH", rate);
} //End Main Method
/**
* Method to calculate total Usage
* #param u1
* #param u2
* #return difference of month 1 and month 2
*/
private static double totalUsage(double u1, double u2) {
return u2 - u1;
}
}
So I would like totalUsage to be accessible in the if statement, that way I can determine the rate and carry on.
I researched on stackoverflow already for a similar posts and came up empty. I researched here: for the if/else statements already as well:
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/if.html
You should declare a variable to stock your total usage, or call the method each time.
With a variable :
double totalUsage = totalUsage(prevMeter, currMeter);
System.out.printf("your usage was: %.1f KwHs", totalUsage);
//calculate rate
if (totalUsage < 500.0) {
rate = .0809;
}
else if (totalUsage > 500.0 && totalUsage < 900.0){
rate = .091;
}
else {
rate = .091;
}
//output rate
System.out.printf("\nYour rate was: %.4f/KwH", rate);
By calling method :
//output total usage
System.out.printf("your usage was: %.1f KwHs", totalUsage(prevMeter, currMeter));
//calculate rate
if (totalUsage(prevMeter, currMeter) < 500.0) {
rate = .0809;
}
else if (totalUsage(prevMeter, currMeter) > 500.0 && totalUsage(prevMeter, currMeter) < 900.0){
rate = .091;
}
else {
rate = .091;
}
//output rate
System.out.printf("\nYour rate was: %.4f/KwH", rate);

How do I do calculations in a separate method then send them back to main for printing?

I am trying to do the calculations for the interest in another method, and I know that I have to make another method outside of main and then put return an the end, but I have no idea what to title this new method and how to go about doing the calculations there. I think it is the while loop that is confusing me. I have done this once before on a different project, so I have an idea of how to do it, but this project isn't anything like the other one and I don't really understand it. Any help is extremely appreciated as I have been working on this for a long time and just want to get it over with. Thanks in advance.
import java.util.Scanner; // This allows for the use of the scanner in the class
public class SavingsAccount // Start of class
{
public static void main(String[]args) // Start of main
{
double P; // These store the amounts that will be used in the accruing interest formula
double i;
double n;
double S = 0;
int timesLooped = 0;
Scanner readConsole = new Scanner(System.in); // This is the scanner
System.out.println("I am a savings account interest calculator."); // Prompts the user for input
System.out.println("How much money have you deposited?");
P = readConsole.nextDouble();
S = P;
System.out.println("Now, what is the annual interest rate? (i.e. .05)");
i = readConsole.nextDouble();
System.out.println("Finally, how long do you plan on having the money in the account?");
n = readConsole.nextDouble();
while (timesLooped <= n)
{
S = S + (P * i);
timesLooped += 1;
}
System.out.println("Your balance in that time span is " + S + "."); // Tells you your ending balance
}
}
Based on your comment, I think you want this:
private static double addInterest(double S, double P, double i)
{
return S + (P * i);
}
...
public static void main()
{
...
while (timesLooped <= n)
{
S = addInterest(S, P, i);
}
EDIT
I made some small improvements just for fun:
I put the entire interest calculation into the function and used exponentiation rather than a loop.
I gave the variables more descriptive names.
I used System.out.format to print the result.
Here's the code:
private static double computeCompoundInterest(double principal, double rate,
double years) {
return principal * Math.pow(1 + rate, years);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("I am a savings account interest calculator.");
System.out.println("How much money have you deposited?");
double principal = scanner.nextDouble();
System.out.println("Now, what is the annual interest rate? (i.e. .05)");
double rate = scanner.nextDouble();
System.out.println("How many years will you hold that money in the account?");
double years = scanner.nextDouble();
double total = computeCompoundInterest(principal, rate, years);
System.out.format("Your balance at the end of that period will be %.2f.\n", years, total);
}

Java: Returning Multiple Values to Main Method In Order To Compute Total

The code is below. The program runs a series of calculations based on data input by the user. My problem is that for the most important thing I'm looking for, total kg CO2 emissions, I continually get an answer of 0.0. What I need is a sum of the individual total emissions as calculated in each method, i.e. the values which are printed with the following: System.out.println(trans); System.out.println(elec); and System.out.println(food);
The total should be something like 25040 or whatever, depending on the value of the inputs provided by the user, but I'm constantly getting a total of 0.0., which is obviously false. Could have something to do with the way I've initialized my variables, or something to do with the limitations of returning values from methods. I just don't know what to do. How should I tackle this? All help greatly appreciated!
import java.util.Scanner;
public class CarbonCalc {
public static void main(String[] args) {
double trans = 0;
double elec = 0;
double food = 0;
giveIntro();
determineTransportationEmission(null);
determineElecticityEmission(null);
determineFoodEmission(null);
calculateTotalEmission(trans, elec, food);
//printReport(trans, elec, food);
}
//Gives a brief introduction to the user.
public static void giveIntro() {
System.out.println("This program will estimate your carbon footprint");
System.out.println("(in metric tons per year) by asking you");
System.out.println("to input relevant household data.");
System.out.println("");
}
//Determines the user's transportation-related carbon emissions.
public static double determineTransportationEmission(Scanner input) {
Scanner console = new Scanner(System.in);
System.out.println("We will first begin with your transportation-related carbon expenditures...");
System.out.print("How many kilometres do you drive per day? ");
double kmPerDay = console.nextDouble();
System.out.print("What is your car's fuel efficiency (in km/litre)? ");
double fuelEfficiency = console.nextDouble();
System.out.println("We now know that the numeber of litres you use per year is...");
double litresUsedPerYear = 365.00 * (kmPerDay / fuelEfficiency);
System.out.println(litresUsedPerYear);
System.out.println("...and the kg of transportation-related CO2 you emit must be...");
//Final calculation of transportation-related kgCO2 emissions.
double trans = 2.3 * litresUsedPerYear;
System.out.println(trans);
System.out.println("");
return trans;
}
//Determines the user's electricity-related carbon emissions.
public static double determineElecticityEmission(Scanner input) {
Scanner console = new Scanner(System.in);
System.out.println("We will now move on to your electricity-related carbon expenditures...");
System.out.print("What is your monthly kilowatt usage (kWh/mo)? ");
double kWhPerMonth = console.nextDouble();
System.out.print("How many people live in your home? ");
double numPeopleInHome = console.nextDouble();
System.out.println("The kg of electricity-related CO2 you emit must be...");
//Final calculation of electricity-related kgCO2 emissions.
double elec = (kWhPerMonth * 12 * 0.257) / numPeopleInHome;
System.out.println(elec);
System.out.println("");
return elec;
}
//Determines the user's food-related carbon emissions.
public static double determineFoodEmission(Scanner input) {
Scanner console = new Scanner(System.in);
System.out.println("We will now move on to your food-related carbon expenditures...");
System.out.print("In a given year, what percentage of your diet is meat? ");
double meat = console.nextDouble();
System.out.print("In a given year, what percentage of your diet is dairy? ");
double dairy = console.nextDouble();
System.out.print("In a given year, what percentage of your diet is fruits and veggies? ");
double fruitVeg = console.nextDouble();
System.out.print("In a given year, what percentage of your diet is carbohydrates? ");
double carbs = console.nextDouble();
//Final calculation of food-related kgCO2 emissions.
System.out.println("The kg of food-related CO2 you emit must be...");
double food = (meat * 53.1 + dairy * 13.8 + fruitVeg * 7.6 + carbs * 3.1);
System.out.println(food);
System.out.println("");
return food;
}
//Calculates total emissions across all sources.
public static double calculateTotalEmission(double trans, double elec, double food) {
System.out.println("Your total kg of CO2 emitted across all sources is equal to...");
double total = trans + elec + food;
System.out.println((double) total);
System.out.println("");
return total;
}
}
Ah!! Thank you very much Lyju. I did the following and it all worked well.
From this:
double trans = 0;
double elec = 0;
double food = 0;
To this:
double trans = determineTransportationEmission(null);
double elec = determineElecticityEmission(null);
double food = determineFoodEmission(null);
The second problem which popped up here had to do with not correctly passing the Scanner parameter to the multiple methods.
I fixed that by adding the following to the main method:
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
double trans = determineTransportationEmission(console);
double elec = determineElecticityEmission(console);
double food = determineFoodEmission(console);
giveIntro();
calculateTotalEmission(trans, elec, food);
}
And because I had three scanner objects, one for each method, I simply removed the Scanners in each and can now pass a single Scanner from my main method to each of the others.

I have to write a source code on software sales. I don't know what my mistake is.

I have to write a program that asks users to enter number of packages purchased. The program should then display the amount of discount and total amount of purchase after discount. I designed by program around this..
import java.util.Scanner;
public class softwareSales
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
double Package = 99, discount, priceBfDiscount, discountPrice, totalPrice;
int quantity;
System.out.println("This is a software sales program");
System.out.println("Enter number of packages");
quantity = input.nextInt();
System.out.println("Enter price of package");
Package = input.nextDouble();
System.out.println("Enter gross price");
priceBfDiscount = input.nextDouble();
priceBfDisc = Package * quantity;
discountPrice = priceBfDisc * discount;
totalPrice = priceBfDisc - discountPrice;
System.out.println("The price before discount is $" + priceBfDisc);
System.out.println("The discount price is $" + discountPrice);
System.out.println("The total price is $" + totalPrice);
if (quantity >= 10 && quantity <= 19)
{
System.out.println("The discount is .20");
}
else if (quantity >=20 && quantity <=49)
{
System.out.println("The discount is .30");
}
else if (quantity >=50 && quantity <=99)
{
System.out.println("The discount is .40");
}
else if (quantity >=100)
{
System.out.println("The discount is .50");
}
}
I don't know what the mistake is. It keeps saying that there is no symbol for priceBfDisc. So if somebody could help me identify my mistake, i would really appreciate it.
Read the error message. You didn't ever declare a priceBfDisc; you declared priceBfDiscount.
double Package = 99, discount, priceBfDiscount, discountPrice, totalPrice;
This is where your problem is, besides the error of priceBfDics not matching.
You need to declare all of these variables
//Either like this
double packageCost;
double discount;
double priceBfDiscount;
double discountPrice,
double total;
// Or like this
double packageCost,discount, priceBfDiscount, discountPrice, total;

Categories

Resources