Cannot find symbol - method: variable(double) - java

My program is not close to being finished, but I am stuck because the compiler gives me an error message "cannot find symbol - method years(double)" in the depreciatonTable method the variable years.
-I am sure it is very obvious, but I cannot seem to figure out why the compiler comes up with an error.
import java.util.Scanner;
public class Problem1
{
public static void main(String args[])
{
double AcquisVal, SalvageVal, years;
Scanner scan = new Scanner(System.in);
Problem1 val = new Problem1();
System.out.println("Enter the Acquisition Value: ") ;
AcquisVal = scan.nextDouble();
System.out.println("Enter the Salvage Value: ");
SalvageVal = scan.nextDouble();
System.out.println("Enter the years of useful life(in whole years): ");
years = scan.nextDouble();
if (AcquisVal < 0)
{
System.out.println("Acquisition value cannot be negative");
}
else if (years < 1){
System.out.println("Years of useful life must be greater than zero");
}
else if (SalvageVal < 0){
System.out.println("Salvage value cannot be negative");
}
else
val.depreciationtable(AcquisVal, SalvageVal, years);
}
public double depreciationtable(double years, double AcquisVal, double SalvageVal)
{
double depreciation, fraction, annDepreciation, AccDepreciation, BookValue;
while (years > 0)
{
fraction = years / (years (years + 1)/ 2);
years--;
}
depreciation = (AcquisVal - SalvageVal) * fraction;
return depreciation;
}
}

There is something wrong in your logic at
fraction = years / (years (years + 1)/ 2). The years (years + 1) part is logically wrong.
Also, look at the Java Naming conventions to use correct variable/method names.

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);
}
}

Simple Discount

Studying for an exam and have a problem,I am a beginner.
Its a discount calculator.
Bag of coffee costs €3.75
10 bags or more 5% discount
20 bags or more 10% discount
What I have so far
import java.util.Scanner;
public class discount {
public static void main (String[] args){
//Scanner input; Keep this as one line. It is good practice
Scanner input = new Scanner(System.in);
double bag;
double discount;
double cost = 3.75;
//Input = new Scanner(System.ini); combined with line above.
System.out.println("Enter Numer of bag");
bag = input.nextDouble();
//If (bag ==>10&&<20) × .05 incorrect Java syntax
if(bag >= 10 && < 20) {
discount = 0.05;
}
else if(bag >= 20) {
discount = 0.10;
}
else {
discount = 0;
}
double finalPrice;
finalPrice = (cost * bag) * (1 - discount);
System.out.println("You ordered " + bag + " bags of coffee.");
System.out.println("Your dicount is " + discount + "%");
System.out.println("You total is: " + finalPrice);
}
}
if(bag >= 10 && < 20)
to
if(bag >= 10 && bag < 20)
An easy mistake for a beginner!
I kinda agree with the lecturer re the editor vs ide while learning the basics. You need to learn to read what the compiler tells you is wrong. And once you know the problem, I think you will agree, the syntax error message above gives a good indication of what is wrong.
I'm usually not in favor of doing assignments for Tom Sawyer students, but in this case I think there's educational opportunity for any beginner who learns to look at the problem differently.
This is a simple class, but it's a good idea to develop good habits if you want to be a programmer.
Pay a lot of attention to code formatting and readability. Think long and hard about names for classes, methods, and variables. You need fewer comments if the names are self-explanatory.
Learn and follow Java coding standards. That will help readability.
Forget about input and output and the user interface - get the functionality right first.
import java.util.LinkedHashMap;
import java.util.Map;
/**
* CoffeePriceCalculator
* User: mduffy
* Date: 7/22/2016
* Time: 7:46 AM
* #link http://stackoverflow.com/questions/38525213/simple-discount
*/
public class CoffeePriceCalculator {
// Is double a good way to represent money? What about units? Conversions?
public static final double DEFAULT_UNIT_PRICE = 3.75; // British pounds
private static final Map<Integer, Double> DISCOUNT_PERCENTAGE;
static {
DISCOUNT_PERCENTAGE = new LinkedHashMap<>();
DISCOUNT_PERCENTAGE.put(10, 0.05);
DISCOUNT_PERCENTAGE.put(20, 0.10);
}
public double calculatePrice(int numBags, double unitPrice) {
if (numBags < 0) throw new IllegalArgumentException("Number of bags must be positive");
if (unitPrice < 0.0) throw new IllegalArgumentException("Unit price must be positive");
double price = numBags*unitPrice;
price -= calculateDiscount(numBags, price);
return price;
}
public double calculatePrice(int numBags) {
return this.calculatePrice(numBags, DEFAULT_UNIT_PRICE);
}
public double calculateDiscount(int numBags, double price) {
if (numBags < 0) throw new IllegalArgumentException("Number of bags must be positive");
if (price < 0.0) throw new IllegalArgumentException("Total price must be positive");
double discount = 0.0;
for (int minBags : DISCOUNT_PERCENTAGE.keySet()) {
if (numBags >= minBags) {
discount = price*DISCOUNT_PERCENTAGE.get(minBags);
break;
}
}
return discount;
}
}
It's not too early to learn about JUnit and Test Driven Development.
import org.junit.Assert;
import org.junit.Test;
/**
* Junit test for CoffeePriceCalculator
* User: mduffy
* Date: 7/22/2016
* Time: 7:50 AM
* #link http://stackoverflow.com/questions/38525213/simple-discount
*/
public class CoffeePriceCalculatorTest {
public static final double TOLERANCE = 1.0e-3;
#Test
public void testCalculatePrice_NoDiscount() {
// setup
CoffeePriceCalculator coffeePriceCalculator = new CoffeePriceCalculator();
int numBags = 5;
// exercise
double actual = coffeePriceCalculator.calculatePrice(numBags);
// assert
Assert.assertEquals(numBags * CoffeePriceCalculator.DEFAULT_UNIT_PRICE, actual, TOLERANCE);
}
#Test
public void testCalculatorPrice_LowDiscount() {
// setup
CoffeePriceCalculator coffeePriceCalculator = new CoffeePriceCalculator();
int numBags = 15;
// exercise
double actual = coffeePriceCalculator.calculatePrice(numBags);
// assert
Assert.assertEquals(numBags * CoffeePriceCalculator.DEFAULT_UNIT_PRICE*0.95, actual, TOLERANCE);
}
#Test
public void testCalculatorPrice_HighDiscount() {
// setup
CoffeePriceCalculator coffeePriceCalculator = new CoffeePriceCalculator();
int numBags = 25;
// exercise
double actual = coffeePriceCalculator.calculatePrice(numBags);
// assert
Assert.assertEquals(numBags * CoffeePriceCalculator.DEFAULT_UNIT_PRICE*0.90, actual, TOLERANCE);
}
#Test(expected = IllegalArgumentException.class)
public void testCalculatePrice_NegativeBags() {
// setup
CoffeePriceCalculator coffeePriceCalculator = new CoffeePriceCalculator();
int numBags = -25;
// exercise
coffeePriceCalculator.calculatePrice(numBags);
}
}
Hopefully your exam is not coming up too soon, because you have a lot of syntax to review.
I don't really like giving straight up answers to homework questions, so I will fix up what you currently have, and perhaps that will point you in the right direction.
Import.java.util.scanner;
public class discount {
public static void main (String[] args){
//Scanner input; Keep this as one line. It is good practice
Scanner input = new Scanner(System.in);
//Float bag;
int bag;
Float discount;
Double cost = 3.75;
//Input = new Scanner(System.ini); combined with line above.
System.out.println("Enter Numer of bag");
bag = input.nextFloat();
//If (bag ==>10&&<20) × .05 incorrect Java syntax
//if(bag >= 10 && < 20) {
if(bag >= 10 && bag < 20) {
discount = 0.05;
}
else if(bag >= 20) {
discount = 0.10;
}
else {
//discount = 0;
discount = 0.0;
}
double finalPrice;
finalPrice = (cost * bag) * (1 - discount);
//System.out.println("You ordered " + bag + " bags of coffee.);
System.out.println("You ordered " + bag + " bags of coffee.");
System.out.println("Your dicount is " + discount + "%");
System.out.println("Your total is: " + finalPrice);
}
}
Remember to keep your code clean so you do not confuse yourself. Make sure you indent your code.
Think about what you are naming your variables, and do not be afraid to refactor them if you come up with something better. Using clear and logical naming will reduce the number of comments you will need to write.
And as I mentioned before, study up on your syntax. There were a lot of syntax errors in your code, which leads me to believe that maybe you are writing your code in notepad or from the command line? If so I would recommend using an IDE such as IntelliJ, NetBeans, or Eclipse. These will underline your syntax errors and point out mistakes that you may not notice straight away.

Java Interests loop with method

I have a method which calulates intrests.
public static float calculateIntrests (float Principal, float RateInPercentage){
float result;
result=Principal*RateInPercentage;
return result;
Now I need a loop to print me how much "money" do I have each year. I have done something like this.
import java.util.Scanner;
public class Aplikacija {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int years = 1;
System.out.println("Principal!");
float Principal = input.nextInt();
System.out.println("Rate!");
int Rate = input.nextInt();
float RateInPercentage = Rate / 100.0f;
float calculate = Caluclateintrests(Principal, rateinPercentage);
while (year <= 5) {
System.out.println("It is: " + (calculate) + " dollars in year" + year + "on your account");
year++;
}
input.close();
}
}
Java is a case sensitive, so if you declared variable, method or class with a specific name then you have to sick with the declared name in order to use it,
So you have declared years but you used year instead
int years = 1;
But used as:
while (year <= 5) {//
So here you can do two of thins:
change the declaration of years to be year.
change the using of that variable to years.
This also goes with RateInPercentage variable, Caluclateintrests method.
You have lots and lots of mistakes. Remember to spell it right and that Java is case-sensitive, therefore you have to keep eye on capital letters.
And few mistakes are not syntax, but in logical matter.
Also the naming convention for Java suppose to start naming variables and methods with lower-case letter.
This is working code, try to learn from it :
import java.util.Scanner;
public class Aplikacija {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int year = 1;
System.out.println("Principal!");
float principal = input.nextInt();
System.out.println("Rate!");
int rate = input.nextInt();
float rateInPercentage = rate / 100.0f;
while (year <= 5) {
principal += calculateIntrests(principal, rateInPercentage);
System.out.println("It is: " + principal + " dollars in year" + year + " on your account");
year++;
}
input.close();
}
public static float calculateIntrests(float principal, float rateInPercentage) {
float result;
result = principal * rateInPercentage;
return result;
}
}
Sample output :
Principal!
100
Rate!
1
It is: 101.0 dollars in year1 on your account
It is: 102.01 dollars in year2 on your account
It is: 103.030106 dollars in year3 on your account
It is: 104.06041 dollars in year4 on your account
It is: 105.10101 dollars in year5 on your account

Else without if error: I dont understand why java isn't recognizing my if statment [duplicate]

This question already has answers here:
Error: 'else' without 'if' [closed]
(3 answers)
Closed 7 years ago.
At line 53 it is giving me an error of else without if. I clearly have an if statement, but i don't know what i'm doing wrong to make java not recognize it. I've tried moving around the braces and nothing is working.
import java.util.Scanner;
import java.text.DecimalFormat;
public class Quiz6
{
public static void displayInfo()
{
System.out.println(
"\n\tAuthor: Allen Watson \n" +
"\tClass: \tCSCI 1250-001 \n" +
"\tDate: \t10/09/2013 \n" +
"\tLab: \tQuiz6 \n");
}
public static double calculatePay(int hourWorked, double hourlyRate)
{
double dPay;
dPay = (hourWorked * hourlyRate);
return dPay;
}
public static void main(String[] args)
{
Scanner Keyboard = new Scanner(System.in);
DecimalFormat dfMoney = new DecimalFormat("$#,##0.00");
String strName;
int iCount;
int iDaysWorked;
int iTotalHoursWorked;
int iSingleDayHours;
double dHourlyRate;
final byte WEEK = 7;
displayInfo();
System.out.print("\tWhat is your name: ");
strName = Keyboard.nextLine();
System.out.print("\n\tHow many days did you work this week: ");
iDaysWorked = Keyboard.nextByte();
System.out.print("\n\tHow much do you make an hour: ");
dHourlyRate = Keyboard.nextDouble();
if(dDaysWorked <= WEEK);
{
for(iCount = 1; iCount <= iDaysWorked ; iCount++)
{
System.out.print("\tHow many hours did you work on the day"+iCount+":");
iSingleDayHours = Keyboard.nextInt();
iSingleDayHours += iTotalHoursWorked;
}
}
else
{
bDaysWorked = 0;
System.out.print("A week can only have seven days");
}
calculatePay(iTotalHoursWorked,dHourlyRate);
System.out.print("Hello "+strName+", you worked a total of "+iTotalHoursWorked+" hours over "+iDaysWorked+" days.");
System.out.print("\nWith am hourly rate of "+dfMoney(dHourlyRate)+" you made "+dfMoney(dPay)+".");
}
}
Here's the problem:
if(dDaysWorked <= WEEK); // remove the ;
That trailing ; is making Java believe that the if statement is finished, and the {} block after it is outside the if condition, consequently the else part has no matching if preceding it.
This is a rather frequent bug, and a hard one to spot. If it weren't for the else block, the code would have compiled correctly, but it would have been wrong. Bottom line: never, ever put a ; in the opening line of an if, for or while statement.
if(dDaysWorked <= WEEK); - remove last ;

Java loan calculator

I'm trying to code a loan calculator. I seem to be having issues. I am trying to get an input from the user and validate the input. I know I am doing it wrong the problem is I'm scratching my head wondering how to do it right.
I get a red line on the d = getDouble(sc, prompt); and the i = getInt(sc, prompt); which I understand I don't have that coded correctly. I'm just unsure how to go about fixing it.
I also have to validate the continue statement which I wasn't to sure the best way to go about that and finally the instructor expects the code to be 80 lines or less which I am right about 80 lines. I guess I'm looking for a better way to do this but being new I'm scratching my head and I'm hoping someone can lend a hand.
As always I really appreciate the help.
import java.util.Scanner;
import java.text.NumberFormat;
public class LoanCalculator
{
public static double getDoubleWithinRange(Scanner sc, String prompt, double min, double max)
{
double d = 0.0;
boolean isValid = false;
while(isValid == false);
{
d = getDouble(sc, prompt);
if (d <= min)
{
System.out.println("Error! Number must be greater tha 0.0");
}
else if (d >= max)
{
System.out.println("Error number must be less than 1000000.0");
}
else
isValid = true;
}
return d;
}
public static int getIntWithinRange(Scanner sc, String prompt, int min, int max)
{
int i = 0;
boolean isvalid = false;
while(isvalid == false)
{
i = getInt(sc, prompt);
if (i <= min)
System.out.println("Error! Number must be more than 0");
else if (i >= max)
System.out.println("Error! Number must be less than 100");
else
isvalid = true;
}
}
public static void main(String[] args)
{
System.out.println("Welcome to the loan calculator");
Scanner sc = new Scanner(System.in);
String choice = "y";
while (choice.equalsIgnoreCase("y"))
{
System.out.println("DATA ENTRY");
double loanAmount = getDoubleWithinRange(sc, "Enter loan amount: ", 0.0, 1000000.0);
double interestRate = getDoubleWithinRange(sc, "Enter yearly interest rate: ", 0, 20);
int years = getIntWithinRange(sc, "Enter number of years: ", 0, 100);
int months = years * 12;
double monthlyPayment = loanAmount * interestRate/
(1 - 1/Math.pow(1 + interestRate, months));
NumberFormat currency = NumberFormat.getCurrencyInstance();
NumberFormat percent = NumberFormat.getPercentInstance();
percent.setMaximumFractionDigits(3);
System.out.println("RESULST");
System.out.println("Loan Amount" + currency.format(loanAmount));
System.out.println("Yearly interest rate: " + percent.format(interestRate));
System.out.println("Number of years: " + years);
System.out.println("Monthly payment: " + currency.format(monthlyPayment));
System.out.println();
System.out.println("Continue? (y/n): ");
choice =sc.next();
System.out.println();
}
}
}
You haven't made the implementation of your getDouble(Scanner,String) and getInt(Scanner,String) that's why you're getting the red line.
since you already have a scanner, and prompt string change it to this
System.out.print(prompt);
d = sc.nextDouble();
and for the integer
System.out.print(prompt);
i = sc.nextInt();
I think getDouble and getInt are string functions so you would have to get a string first then call those methods. However, since you have a scanner, I assume you want to use that with the nextXXX methods:
Scanner sc = new Scanner (System.in);
double d = sc.nextDouble();
You can use this complete snippet for educational purposes:
import java.util.Scanner;
class Test {
public static void main (String args[]) {
Scanner sc = new Scanner (System.in);
System.out.print("Enter your double: ");
double d = sc.nextDouble();
System.out.print("Enter your integer: ");
int i = sc.nextInt();
System.out.println("You entered: " + d + " and " + i);
}
}
Transcript:
Enter your double: 3.14159
Enter your integer: 42
You entered: 3.14159 and 42
Basically, the process is:
Instantiate a scanner, using the standard input stream.
Use print for your prompts.
Use the scanner nextXXX methods for getting the input values.
A little more assistance here, based on your comments.
In your main function, you have:
double loanAmount = getDoubleWithinRange(sc, "Enter loan amount: ", 0.0, 1000000.0)
and that function has the prototype:
public static double getDoubleWithinRange(
Scanner sc, String prompt, double min, double max)
That means those variables in the prototype will be set to the values from the call. So, to prompt for the information, you could use something like (and this is to replace the d = getDouble(sc, prompt); line):
System.out.print(prompt);
double d = sc.nextDouble();
And there you have it, you've prompted the user and input the double from them. The first line prints out the prompt, the second uses the scanner to get the input from the user.
As an aside, your checks for the minimum and maximum are good but your error messages have hard-coded values of 0 and 100K. I would suggest that you use the parameters to tailor these messages, such as changing:
System.out.println("Error! Number must be greater tha 0.0");
into:
System.out.println("Error! Number must be greater than " + min);
That way, if min or max change in future , your users won't get confused :-)
I'll leave it up to you to do a similar thing for the integer input. It is your homework, after all :-)

Categories

Resources