Error with Income Tax program in Java using JCreator - java

I am getting an error that says one of the variables I have used are not initialized but upon reviewing the code I realize that I have in fact initialized the variable so I don't understand why I keep getting the error.
This is the error:
error: variable tax might not have been initialized
avgtax = (tax/sal)*100;
^
This is the code:
import java.util.*;
public class Taxable {
final static double first15=0.1;
final static double next20=0.2;
final static double over35=0.25;
final static double tax_inc=0.8;
public static void main(String[] args) {
double sal, TaxInc;
double tax, avgtax;
Scanner in = new Scanner(System.in);
System.out.printf("Enter Salary: ");
sal = in.nextDouble();
TaxInc = sal*tax_inc;
if (TaxInc > 0 && TaxInc <= 15000)
tax = TaxInc*first15;
else if (TaxInc > 15000 && TaxInc <= 35000)
tax = (15000 * first15) + ((TaxInc - 15000) * next20);
else if (TaxInc > 35000)
tax = (15000 * first15) + (20000 * next20) + ((TaxInc - 35000) * over35);
else
System.out.printf("\nInvalid Salary Figure.");
avgtax = (tax/sal)*100;
System.out.printf("\nAt a salary of: %3.2f\nTax to be paid is:"
+ " %3.2f\nAverage Tax Rate is: %3.1f", sal, tax, avgtax);
}
}
Any help would be greatly appreciated.

This has some fixes to your code so it compiles and runs as expected
public class Taxable {
final static double first15=0.1;
final static double next20=0.2;
final static double over35=0.25;
final static double tax_inc=0.8;
public static void main(String[] args) {
double sal;
double taxInc;
double tax = 0;
double avgtax;
Scanner in = new Scanner(System.in);
System.out.printf("Enter Salary: ");
sal = in.nextDouble();
taxInc = sal*tax_inc;
if (taxInc > 0 && taxInc <= 15000) tax = taxInc*first15;
else if (taxInc > 15000 && taxInc <= 35000) tax = (15000 * first15) + ((taxInc - 15000) * next20);
else if (taxInc > 35000) tax = (15000 * first15) + (20000 * next20) + ((taxInc - 35000) * over35);
else System.out.printf("\nInvalid Salary Figure.");
avgtax = (tax/sal)*100;
System.out.printf("\nAt a salary of: %3.2f\nTax to be paid is: %3.2f\nAverage Tax Rate is: %3.1f", sal, tax, avgtax);
}
}
However its not nicely structured ... I suggest reading Java naming convention and programming standards
EDIT:
Although you have accepted an answer, i suggest looking at this code sample, its written in slightly more readable way :)
import java.util.Scanner;
public class Taxable {
private final static double first15 =0.1;
private final static double next20 =0.2;
private final static double over35 =0.25;
private final static double tax_inc =0.8;
private double sal;
private double taxInc;
private double tax = 0;
private double avgtax;
public static void main(String[] args) {
System.out.printf("Enter Salary: ");
Scanner in = new Scanner(System.in);
Taxable taxable = new Taxable();
taxable.setSal(in.nextDouble());
System.out.println(taxable.calculateTax());
}
private String calculateTax(){
setTaxInc(getSal()*tax_inc);
if (getTaxInc() > 0 && getTaxInc() <= 15000){
setTax(getTaxInc()*first15);
}
else if (getTaxInc() > 15000 && getTaxInc() <= 35000){
setTax((15000 * first15) + ((getTax() - 15000) * next20));
}
else if (getTaxInc() > 35000){
setTax((15000 * first15) + (20000 * next20) + ((getTax() - 35000) * over35)) ;
}
else {
System.out.printf("\nInvalid Salary Figure.");
}
setAvgtax((getTax()/getSal())*100);
String calculation = "\n At a salary of: " + getSal() + "\n Tax to be paid is: " + getTax() + "\n Average Tax Rate is: " + getAvgtax();
return calculation;
}
public double getSal() {
return sal;
}
public void setSal(double sal) {
this.sal = sal;
}
public double getTaxInc() {
return taxInc;
}
public void setTaxInc(double taxInc) {
this.taxInc = taxInc;
}
public double getTax() {
return tax;
}
public void setTax(double tax) {
this.tax = tax;
}
public double getAvgtax() {
return avgtax;
}
public void setAvgtax(double avgtax) {
this.avgtax = avgtax;
}
}

Tax is not initialized and the error is due to the if loops.
If by any chance all if's fail, Tax will not get a value.
just put double Tax = 0;

Related

Calculating taxes using specific values

I am having trouble understanding how to make my program calculate these tax numbers correctly
If Single and taxable income is over
but not over
the tax is
of the amount over
$0
$8,000 10% $0
$8,000 $32,000 $800 + 15% $8,000
$32,000
$4,400 + 25% $32,000
If married and taxable income is over but not over the tax is of the amount over
$0 $16,000 10% $0
$16,000 $64,000 $1,600 + 15% $16,000
$64,000
$8,800 + 25% $64,000
You should prompt the user for their filing status and their taxable income. The user should enter 'S' for single filers and 'M' for married filers.
An example would be if the taxpayer is single and earns $10,000. They would pay $800 plus 15% of 2000 (10,000 - 8,000).
this is what I have so far
public class Income_tax
{
public static final int SINGLE = 1;
public static final int MARRIED = 2;
private static final double RATE1 = 0.10;
private static final double RATE1_SINGLE_LIMIT = 8000;
private static final double RATE1_MARRIED_LIMIT = 16000;
private static final double RATE2_SINGLE_LIMIT = 32000;
private static final double RATE2_MARRIED_LIMIT = 64000;
private static final double RATE3_SINGLE_LIMIT = 60000;
private static final double RATE3_MARRIED_LIMIT = 150000;
private static final double RATE2 = 0.15;
private static final double RATE3 = 0.25;
private double income;
private int status;
public Income_tax(double anIncome, int aStatus)
{
income = anIncome;
status = aStatus;
}
public double getTax()
{
double tax1 = 0;
double tax2 = 0;
if (status == SINGLE)
{
if (income <= RATE1_SINGLE_LIMIT)
{
tax1 = RATE1 * income;
}
else
{
tax1 = RATE1 * RATE1_SINGLE_LIMIT;
tax2 = RATE2 * (income - RATE1_SINGLE_LIMIT);
}
}
if (income <= RATE3_SINGLE_LIMIT)
{
tax1 = RATE3 * income;
if (income <= RATE1_MARRIED_LIMIT)
{
tax1 = RATE1 * income;
}
if (income <= RATE3_MARRIED_LIMIT)
{
tax1 = RATE3 * income;
}
else
{
tax1 = RATE1 * RATE1_MARRIED_LIMIT;
tax2 = RATE2 * (income - RATE1_MARRIED_LIMIT);
}
if (status == SINGLE)
{
if (income <= RATE2_SINGLE_LIMIT)
{
tax1 = RATE2 * income;
}
else
{
tax1 = RATE1 * RATE2_SINGLE_LIMIT;
tax2 = RATE1 * (income - RATE2_SINGLE_LIMIT);
}
}
else
{
if (income <= RATE2_MARRIED_LIMIT)
{
tax1 = RATE2 * income;
}
else
{
tax1 = RATE2 * RATE2_MARRIED_LIMIT;
tax2 = RATE1 * (income - RATE2_MARRIED_LIMIT);
}
}
return tax1 + tax2;
}
return tax2 + tax1;
}
}
my calculator class is
import java.util.Scanner;
public class TaxCalculator {
#SuppressWarnings("resource")
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Please enter your anual income [per year]: ");
double income = in.nextDouble();
System.out.print("Please enter S for Single and M for Married (S/M) ");
String input = in.next();
int status;
if (input.equals("M"))
{
status = Income_tax.MARRIED;
}
else
{
status = Income_tax.SINGLE;
}
Income_tax aTaxReturn = new Income_tax(income, status);
System.out.println(" Your tax is: "
+ aTaxReturn.getTax());
}
}
I'm not really sure why you are calling 'aTaxReturn' as an Object in your main method, that seems a bit unnecessary. You could just call it as a regular method.
One way that I would do it is have 2 seperate methods, one for single and one for married.
Then in each separate method you can break down the tax calculations, so for example:
public class Income_tax {
private static final double RATE1 = 0.10;
private static final double RATE1_SINGLE_LIMIT = 8000;
private static final double RATE1_MARRIED_LIMIT = 16000;
private static final double RATE2_SINGLE_LIMIT = 32000;
private static final double RATE2_MARRIED_LIMIT = 64000;
private static final double RATE3_SINGLE_LIMIT = 60000;
private static final double RATE3_MARRIED_LIMIT = 150000;
private static final double RATE2 = 0.15;
private static final double RATE3 = 0.25;
//private double income; Don't need these since you're not making an object
//private int status; Don't need these since you're not making an object
//Default constructor since you don't need to make an object
public Income_tax() {
}
public double getTaxSingle(double income) {
//Different if statements for tax calculations
}
public double getTaxMarried(double income) {
//Different if statements for tax calculations
}
}
Then in the main method you can call it like this:
public static double getTaxRateSingle(double income) {
return Income_tax.getTaxSingle(income);
}
public static double getTaxRateMarried(double income) {
return Income_tax.getTaxMarried(income);
}
This way you don't need to create unnecessary objects and you can minimize the code while maintaining simplicity.
One more tip: You should brush up on Java naming conventions

Create an array list in java and store values tied to an employee name

I have a program that calculates an employees annual salary based upon there base salary and commission sales. I want to take the program a step further and create an arrayList that will ask for the employee name and then create an array, store the values from the program and print out those values for each employee name inputted.
I imagine that I need to create a for or a else loop to collect the data. Problem is I'm not sure where to do that and how to create the array. I have two classes:
1 class for my commission variable's and calculations:
package Commissions;
public class Calculations {
double totalSales;
private double comRate = 0.025;
private double annualSal = 80000;
private double salesTarget = 120000;
private double acceleration = 0.015;
private double compensation;
public Calculations (double TotalSales) {
this.totalSales = totalSales;
}
public double getCommissionCalc () {
if (totalSales >= salesTarget) {
compensation = (annualSal + (totalSales * (comRate + acceleration)));
return compensation;
} else if (totalSales >= salesTarget * .8) {
compensation = (annualSal + (totalSales * comRate));
return compensation;
} else {
compensation = annualSal;
return compensation;
}
}
}
1 class for my main and user input
package Commissions;
import java.text.NumberFormat;
import java.util.*;
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 the employee name: ");
long empName = input.nextLong();
mediaArray[empName];
System.out.println("Enter your total sales for the year: ");
double totalSales = input.nextDouble();
System.out.println("\r");
Calculations c = new Calculations (totalSales);
System.out.println("Your Total compensation with your annual sales is: " + nf.format(c.getCommissionCalc()));
System.out.println("\r");
System.out.println("If you were to increase your sales you could earn even more money!");
System.out.println("\r");
double i = totalSales + 5000;
double finish = totalSales * 1.5;
while (i <= finish) {
c.totalSales = i;
System.out.println("If you were to increase your sales commission to " + nf.format(i) + " you could earn: " + nf.format(c.getCommissionCalc()));
i = i + 5000;
}
}
}
Here is the code as per my understanding of your problem, had to correct few things as you are saying enter name but taking long as input:
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Paycheck {
public static void main(String[] args) {
List<Employee> empList = new ArrayList<Employee>();
while (true) {
Scanner input = new Scanner(System.in);
NumberFormat nf = NumberFormat.getCurrencyInstance();
System.out.println("Enter the employee name (enter exit to exit): ");
String empName = input.nextLine();
// mediaArray[empName];
if(empName.equals("exit")) {
break;
}
System.out.println("Enter your total sales for the year: ");
double totalSales = input.nextDouble();
Calculations c = new Calculations(totalSales);
System.out
.println("Your Total compensation with your annual sales is: "
+ nf.format(c.getCommissionCalc()));
System.out.println("\r");
System.out
.println("If you were to increase your sales you could earn even more money!");
System.out.println("\r");
double i = totalSales + 5000;
double finish = totalSales * 1.5;
while (i <= finish) {
c.totalSales = i;
System.out
.println("If you were to increase your sales commission to "
+ nf.format(i)
+ " you could earn: "
+ nf.format(c.getCommissionCalc()));
i = i + 5000;
}
System.out.println("\r");
//store employee data into arraylist
empList.add(new Employee(empName, i));
}
for(Employee emp : empList) {
System.out.println("Employee Name: " + emp.getName() + " Total Sales: " + emp.getSales());
}
}
}
class Employee {
private String name;
private Double sales;
public Employee(String empName, double totalSales) {
this.name = empName;
this.sales = totalSales;
}
public Double getSales() {
return sales;
}
public void setSales(Double sales) {
this.sales = sales;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

How to pass a variable between methods without parameters and arguments

I'm having a bit of an issue with a school project of mine. We're supposed to write a Loan class that will do things associated with, well, loans, such as return the monthly payment and the total payment on the loan. My problem is that I have specific instructions for this code that I absolutely cannot go outside of.
Here's the code:
import java.util.Scanner;
import java.text.DecimalFormat;
import java.lang.Math;
public class Loan
{
public double annualInterestRate = 0;
public int numberOfYears = 0;
public double loanAmount = 0;
public Loan()
{
annualInterestRate = 0.025;
numberOfYears = 1;
loanAmount = 1000;
}
public Loan(double interestRate, int numYears, double amount)
{
setRate(interestRate);
setYears(numYears);
setLoanAmount(amount);
}
public void setRate(double interest)
{
DecimalFormat percent = new DecimalFormat( "0.0%" );
if(interest > 25 || interest < 0)
{
System.out.println("WARNING: Invalid annual interest rate: " + percent.format(interest) + ".");
System.out.println("Current value not changed: " + percent.format(annualInterestRate * 100) + ".");
}
else
{
annualInterestRate = interest;
}
}
public void setYears(int years)
{
if(years > 30 || years <= 0)
{
System.out.println("WARNING: Invalid number of years: " + years + ".");
System.out.println("Current value not changed: " + numberOfYears + ".");
}
else
{
numberOfYears = years;
}
}
public void setLoanAmount(double amnt)
{
DecimalFormat loan = new DecimalFormat( "$#,##0.00" );
if(amnt <= 0)
{
System.out.println("WARNING: Invalid loan amount: " + loan.format(amnt) + ".");
System.out.println("Current value not changed: " + loan.format(amnt) + ".");
}
else
{
loanAmount = amnt;
}
}
public double getAnnualInterestRate()
{
return annualInterestRate;
}
public int getNumberOfYears()
{
return numberOfYears;
}
public double getLoanAmount()
{
return loanAmount;
}
public double getMonthlyPayment()
{
double monthly = annualInterestRate/12;
double monthlyPayment = (loanAmount * monthly)/1 - (1/(1 + monthly));
monthlyPayment = Math.pow(monthlyPayment, 12);
return monthlyPayment;
}
public double getTotalPayment()
{
double totalPayment = getmonthlyPayment() * 12;
return totalPayment;
}
public String toString()
{
DecimalFormat percent = new DecimalFormat( "0.0%" );
DecimalFormat loan = new DecimalFormat( "$#,##0.00" );
String interestRate = percent.format(annualInterestRate);
String numOfYears = Integer.toString(numberOfYears);
String loanAmnt = loan.format(loanAmount);
String total = "Annual Interest Rate:\t" + interestRate + "\nNumber of Years:\t\t" + numOfYears + "\nLoan Amount:\t\t\t" + loanAmnt;
return total;
}
}
My problem is with the getTotalPayment method. It can't access the monthlyPayment variable without me either declaring monthlyPayment as a field, like annualInterestRate, or passing it to the getTotalPayment method. The issue is, getTotalPayment is not allowed to have parameters, and we aren't allowed to have any more fields than the three she instructed us to have, which are the three you'll see declared in the beginning of the code.
So, my question: is there a way to make the variable monthlyPayment accessible to getTotalPayment, without making monthlyPayment a field or giving getTotalPayment a parameter?
You have a spelling error in your getTotalPayment() method.
What your trying to do is call the method getmonthlyPayment() when you should be calling getMonthlyPayment().
Incase you missed the suttle difference in my answer you have a lowercase 'm' when you want an uppercase 'M'.
Im not entirety sure if this is your problem, but its the only syntax error my IDE is telling me.
In your revised code you need upper case M in call to getMonthlyPayment().

Semicolon expected error in method header

I know that in method headers you aren't supposed to end it with a semicolon; however, all my method headers display the same error: ; expected. This is for the end of the header as well as between two parameters. How would I fix this?
import java.util.Scanner;
import java.text.DecimalFormat;
// This program will calculate the cost of someone's order at a coffee shop with applied possible discounts and tax
public class CoffeeShopWithMethods
{
public static void main (String [] args)
{
double cost = 0;
double discount = 0;
// Scanner allows user to enter values
Scanner user_input = new Scanner(System.in);
String username;
System.out.print("\nEnter your username: ");
username = user_input.next( );
System.out.print ("\nWelcome to Casey's Classic Coffee, " + username + "! \n");
//call methods
displayMenu();
displayOutput(cost, discount, Discounted_cost, tax, Total_cost);
System.out.println("\nThank you " + username + "! Have a nice day!");
}
//outputs the menu to the screen
public static void displayMenu()
{
System.out.println ("\n\tItem\t\tCost\n\t1. Coffee\t$1.50\n\t2. Latte\t$3.50\n\t3. Cappuccino\t$3.25\n\t4. Espresso\t$2.00");
}
//prompts the user to enter item number, returns user input
public static int getItemNumber(int number) //error: ; expected
{
int number;
Scanner number = new Scanner(System.in);
System.out.print ("\nPlease enter the desired item number: ");
number = user_input.nextInt();
return number;
}
//prompts user to enter quantity, returns user input
public static int getQuantity (int quantity) //error: ; expected
{
System.out.print ("\nPlease enter the quantity: ");
quantity = user_input.nextInt();
return quanity;
}
//takes the item number and quantity and returns the subtotal
public static double computeSubTotal (double cost) //error: ; expected
{
int number = getItemNumber(number);
int quantity = getQuantity(quantity);
// Used final double in order to make coffee shop items constant
final double COFFEE = 1.50;
final double LATTE = 3.50;
final double CAPPUCCINO = 3.25;
final double ESPRESSO = 2.00;
double cost = 0;
if (number == 1)
cost = quantity * COFFEE;
else if (number == 2)
cost = quantity * LATTE;
else if (number == 3)
cost = quantity * CAPPUCCINO;
else if (number == 4)
cost = quantity * ESPRESSO;
}
//takes the subtotal and returns true if the user earned a discount; otherwise, returns false
public static boolean discountCheck (double cost) //error: ; expected
{
boolean status;
if (cost >= 10)
{
status = true;
}
else if (cost < 10)
{
status = false;
}
return status;
}
//takes the subtotal and returns the dollar amount of the discount earned by the user
public static double computeDiscount (double cost, double discount) //error: ; expected
{
if (discountCheck() == true)
{
discount = cost * 0.10;
}
else if (discountCheck() != true)
{
discount = 0;
}
return discount;
}
//takes the subtotal and the discount amount and returns the price after the discount is applied
public static double computePriceAfterDiscount (double cost, double discount) //error: ; expected
{
double discount = 0;
double Discounted_cost = 0;
Discounted_cost = cost - discount;
return Discounted_cost;
}
//takes the prices after the discount is applied and tax rate and returns the tax amount
public static double computeTax(double Discounted_cost) //error: ; expected
{
tax = Discounted_cost * 0.07;
return tax;
}
//takes the price after the discount is applied and the tax amount and returns the final total
public static double computeTotal(double Discounted_cost, double tax) //says ; expected
{
Total_cost = Discounted_cost + tax;
return Total_cost;
}
//takes the subtotal, discount amount, price after discount, tax, and final total and displays all the lines of output to the user
public static void displayOutput(double cost, double discount, double Discounted_cost, double tax, double Total_cost) //says ; expected at the end of method header
{
//call methods
double cost = computeSubTotal(cost);
double discount = computeDiscount(cost, discount);
double Discounted_cost = computePriceAfterDiscount(cost, discount);
double tax = computeTax(Discounted_cost);
double Total_cost = computeTotal(Discounted_cost, tax);
System.out.printf ("\nTotal before discount and tax: $%.2f\n ", cost);
System.out.printf("\nCalculated discount: $%.2f\n", discount);
System.out.printf("\nTotal after special discount: $%.2f\n", Discounted_cost);
System.out.printf("\nTax: $%.2f\n", tax);
System.out.printf ("\nTotal cost: $%.2f\n", Total_cost);
}
} //error:reached end of the file while parsing
1)You are using the variables with out declaring:
for eg: compare this snippet with your code snippet.
public static double computeTotal(double Discounted_cost, double tax)
{
double Total_cost = Discounted_cost + tax;
return Total_cost;
}
2)You are invoking undefined methods.
for eg:
you are calling discountCheck() but you have defined like this.
and you have not initialized local variables before using
public static boolean discountCheck (double cost){
boolean status;
if (cost >= 10)
{
status = true;
}
else if (cost < 10)
{
status = false;
}
return status;
}
in the above method status should be initialized.
3) You are declaring duplicate variables that are already available to the methods via parameters.
see the code defined by you here:
public static void displayOutput(double cost, double discount, double Discounted_cost, double tax, double Total_cost)
{
//call methods
double cost = computeSubTotal(cost);
double discount = computeDiscount(cost, discount);
double Discounted_cost = computePriceAfterDiscount(cost, discount);
double tax = computeTax(Discounted_cost);
double Total_cost = computeTotal(Discounted_cost, tax);
System.out.printf ("\nTotal before discount and tax: $%.2f\n ", cost);
System.out.printf("\nCalculated discount: $%.2f\n", discount);
System.out.printf("\nTotal after special discount: $%.2f\n", Discounted_cost);
System.out.printf("\nTax: $%.2f\n", tax);
System.out.printf ("\nTotal cost: $%.2f\n", Total_cost);
}
I would start by extracting your MenuItem(s) into an enum like,
static enum MenuItem {
COFFEE("Coffee", 1.5), LATTE("Latte", 3.5), CAPPUCINO("Cappuccino",
3.25), ESPRESSO("Espresso", 2);
MenuItem(String name, double cost) {
this.name = name;
this.cost = cost;
}
double cost;
String name;
public String toString() {
return String.format("%s $%.2f", name, cost);
}
}
Then your compiler errors were mainly due to declaring duplicate local variable names. I was able to fix the compiler errors and produce something that looks like what you want with,
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter your username: ");
String username = scan.nextLine();
System.out.printf("Welcome to Casey's Classic Coffee, %s!%n", username);
displayMenu();
displayOutput(scan);
System.out.printf("Thank you %s! Have a nice day!", username);
}
// outputs the menu to the screen
public static void displayMenu() {
MenuItem[] items = MenuItem.values();
for (int i = 0; i < items.length; i++) {
System.out.printf("%d %s%n", i + 1, items[i]);
}
}
public static int getItemNumber(Scanner scan) {
System.out.println("Please enter the desired item number: ");
return scan.nextInt();
}
public static int getQuantity(Scanner scan) {
System.out.println("Please enter the quantity: ");
return scan.nextInt();
}
public static double computeSubTotal(Scanner scan) {
int number = getItemNumber(scan);
int quantity = getQuantity(scan);
return quantity * MenuItem.values()[number - 1].cost;
}
public static boolean discountCheck(double cost) {
return (cost >= 10);
}
public static double computeDiscount(double cost) {
if (discountCheck(cost)) {
return cost * 0.10;
}
return 0;
}
public static double computePriceAfterDiscount(double cost, double discount) {
return cost - discount;
}
public static double computeTax(double Discounted_cost) {
return Discounted_cost * 0.07;
}
public static double computeTotal(double Discounted_cost, double tax) {
return Discounted_cost + tax;
}
public static void displayOutput(Scanner scan) {
double cost = computeSubTotal(scan);
double discount = computeDiscount(cost);
double Discounted_cost = computePriceAfterDiscount(cost, discount);
double tax = computeTax(Discounted_cost);
double Total_cost = computeTotal(Discounted_cost, tax);
System.out.printf("Total before discount and tax: $%.2f%n", cost);
System.out.printf("Calculated discount: $%.2f%n", discount);
System.out.printf("Total after special discount: $%.2f%n",
Discounted_cost);
System.out.printf("Tax: $%.2f%n", tax);
System.out.printf("Total cost: $%.2f%n", Total_cost);
}
Here is your entire code corrected and working: http://ideone.com/ta0R21
I really recommend redesigning this. I suggest making use of global variable in some instances.
like the Scanner object. Instead of initializing a new Scanner each method call, use a global
one to handle the entire job

return issue for method

I am having an issue with a method returning to the main method. It is saying that amount in "return amount" cannot be resolved to a variable. Where am I off on this??
This is the message I get:
Multiple markers at this line
- Void methods cannot return a
value
- amount cannot be resolved to a
variable
Here is the code:
import java.util.Scanner;
public class Investment {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the amount invested: ");
double amount = input.nextDouble();
System.out.print("Enter the annual interest rate: ");
double interest = input.nextDouble();
int years = 30;
System.out.print(futureInvestmentValue(amount, interest, years)); //Enter output for table
}
public static double futureInvestmentValue(double amount, double interest, int years) {
double monthlyInterest = interest/1200;
double temp;
double count = 1;
while (count < years)
temp = amount * (Math.pow(1 + monthlyInterest,years *12));
amount = temp;
System.out.print((count + 1) + " " + temp);
}
{
return amount;
}
}
You curly braces are not correct. The compiler - and me - was confused about that.
This should work (at least syntactically):
import java.util.Scanner;
public class Investment {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the amount invested: ");
double amount = input.nextDouble();
System.out.print("Enter the annual interest rate: ");
double interest = input.nextDouble();
int years = 30;
System.out.print(futureInvestmentValue(amount, interest, years));
}
public static double futureInvestmentValue(
double amount, double interest, int years) {
double monthlyInterest = interest / 1200;
double temp = 0;
double count = 1;
while (count < years)
temp = amount * (Math.pow(1 + monthlyInterest, years * 12));
amount = temp;
System.out.print((count + 1) + " " + temp);
return amount;
}
}
Remove amount from its own scope As a start. Also from the method futureInvestmentValue, you take in amount as an argument but the value is never modified so you're returning the same value being passed which is most likely not the desired outcome.
remove return amount from its own scope
the method futureInvestmentValue... You can't modify any of the parameters inside the method so you have to declare another variable besides amount inside the method (maybe it's the temp variable you keep using) and return that instead
when you return something, the return statement is always inside the method. Never outside it while inside its own braces (never seen this before...)
import java.util.Scanner;
public class Investment {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the amount invested: ");
double amount = input.nextDouble();
System.out.print("Enter the annual interest rate: ");
double interest = input.nextDouble();
int years = 30;
System.out.print(futureInvestmentValue(amount, interest, years)); //Enter output for table
}
public static double futureInvestmentValue(double amount, double interest, int years) {
double monthlyInterest = interest/1200;
double temp;
double count = 1;
while (count < years) {
temp = amount * (Math.pow(1 + monthlyInterest,years *12));
System.out.print((count + 1) + " " + temp);
}
return amount;
}
}

Categories

Resources