So I'm supposed to create a program where I have a gas station with 5 gas pumps and and I don't know how to keep track of the statistics, the program correctly subtracts the amount of gas left from the type of gas tank but when the next customer pumps gas the statistics get erased? any help would be appreciated, here is my code. keep in my mind this is part of a 5 class program and this is only one part.
import java.util.Random;
import java.util.Scanner;
public class GasPump
{
static Scanner Input = new Scanner (System.in);
private static double totalRevenue;
private static double currentPurchase;
//private int currentGasType;
private static double currentGasType;
private static double currentGasAmount;
private Client currentClient;
private int clock;
private static double regularTank;
private static double plusTank;
private static double supremeTank;
//private static double amountLeftInTank;
public void updatePump()
{
if (currentClient != null)
{
clock--;
if (clock == 0)
{
//totalRevenue += currentPurchase;
totalRevenue = totalRevenue + currentPurchase;
resetPump ( );
}
}
}
public void resetPump ( )
{
clock = 0;
currentClient = null;
currentPurchase = 0;
//currentGasType = "";
currentGasType = 0;
currentGasAmount = 0;
}
public boolean pumpOpen()
{
return (clock == 0) && (currentClient == null);
}
public static double getCurrentGasType()
{
regularTank = 1000;
plusTank = 1000;
supremeTank = 1000;
//Scanner Input = new Scanner(System.in);
System.out.println("What type of gas would you like?");
System.out.println("Regular , Plus or Premium");
System.out.println("1)Regular: $2.99 per gallon; 2)Plus: $3.99 per gallon; 3)Premium: $4.99 per gallon");
currentGasType = Input.nextDouble();
Random gen = new Random ();
//currentGasAmount = gen.nextDouble ()* 45;
currentGasAmount = gen.nextDouble()*50;
double roundOff = (double) Math.round(currentGasAmount * 100) / 100;
//System.out.println("How many gallons would you like?");
//currentGasAmount = Input.nextDouble();
if (currentGasType == 1)
{
currentGasType = 2.99;
regularTank = regularTank - currentGasAmount;
}
else if (currentGasType == 2)
{
currentGasType = 3.99;
plusTank = plusTank - currentGasAmount;
}
else
{
currentGasType = 4.99;
supremeTank = supremeTank - currentGasAmount;
}
System.out.println("# of gallons purchased: " + currentGasAmount);
System.out.println("Amount of regular gas left: " + regularTank);
System.out.println("Amount of plus gas left: " + plusTank);
System.out.println("Amount of supreme gas left: " + supremeTank);
return currentGasType;
}
/*public static double getCurrentGasAmount() {
Random gen = new Random ();
currentGasAmount = gen.nextDouble ()* 50;
//System.out.println("How many gallons would you like?");
//currentGasAmount = Input.nextDouble();
System.out.println("# of gallons purchased: " + currentGasAmount);
return currentGasAmount;
}
*/
public static double getCurrentPurchase()
{
currentPurchase = currentGasType * currentGasAmount;
return currentPurchase;
}
public static double getTotalRevenue() {
totalRevenue += currentPurchase;
System.out.println("Total revenue so far is " + totalRevenue);
return totalRevenue;
}
/*public static double getAmountLeftInTank()
{
regularTank = 1000;
plusTank = 1000;
supremeTank = 1000;
if (currentGasAmount == 1)
if (currentGasType == 1)
{
//regularTank = regularTank - currentGasAmount;
}
else if (currentGasType == 2)
else if (currentGasAmount == 2)
{
//plusTank = plusTank - currentGasAmount;
}
else
{
supremeTank = supremeTank - currentGasAmount;
}
System.out.println("Amount of regular gas left: " + regularTank);
System.out.println("Amount of plus gas left: " + plusTank);
System.out.println("Amount of supreme gas left: " + supremeTank);
return amountLeftInTank;
}
*/
public void serveAClient (Client aClient)
{
clock = 10;
currentClient = aClient;
GasPump.getCurrentGasType();
System.out.println("Your total is " + GasPump.getCurrentPurchase());
GasPump.getTotalRevenue();
//GasPump.getAmountLeftInTank();
/*
* design get methods
* ask client what type of gas he wants
* add more code here
*/
// add the total here
}
}
Don't use static fields for the data stored in GasPump.
static fields are singletons, they only have a single value shared across all instances of GasPump. This means that if you have multiple instances of GasPump, then calling reset will reset all of the gas pumps.
By removing the keyword static from each of the fields, then there will be a separate copy of the field held for each of the GasPump's. And thus calling reset will only wipe the fields for that one instance of GasPump.
The following diagram may help you to visualise the difference:
In this example, count has been shared across instances c1 and c2 of CircleWithCount.
You can read more detail about using the static keyword on fields here: What does the 'static' keyword do in a class?
Related
When I run the program and and put in a couple mortgages and then end the program it prints out the entire array of objects, mortgageArray[], but for some reason it is only printing out the last mortgage you entered. Not sure why can anybody help me out? I think the problem may lie when instantiating the objects into the array.
Mortgage Class
import java.util.*;
import java.lang.Math.*;
import java.text.DecimalFormat;
public class Mortgage {
private static int loanAmount;
private static int term;
private static double interestRate;
private static String accountNum;
private static String lastName;
private static double monthlyPayment;
private static double totalPayment;
public Mortgage(int loanAmount1, int term1, double interestRate1, String accountNum1){
loanAmount = loanAmount1;
term = term1;
interestRate = interestRate1;
accountNum = accountNum1;
}
public void promotional(){
Mortgage m = new Mortgage();
m.storeLastName();
m.storeAccountNum();
lastName = getLastName();
accountNum = getAccountNum();
monthlyPayment = m.calcMonthlyPayment();
totalPayment = m.calcTotalPayment();
}
public void unique(){
Mortgage m = new Mortgage();
m.storeLastName();
m.storeAccountNum();
m.storeLoanAmount();
m.storeInterestRate();
m.storeTerm();
monthlyPayment = m.calcMonthlyPayment();
totalPayment = m.calcTotalPayment();
}
public Mortgage(){
//dummy constructor
}
public static int getLoanAmount(){
return loanAmount;
}
public void storeLoanAmount(){
Scanner s = new Scanner(System.in);
System.out.println("Enter the amount of the loan (Ex:75000): ");
int loanAmount1 = s.nextInt();
while(loanAmount1 < 75000 || loanAmount1 > 1000000){
System.out.println("\tValid Loan Amounts are $75000-$1000000");
System.out.println("\tPlease re-enter loan amount without $ or commas (Ex:75000): ");
loanAmount1 = s.nextInt();
}
loanAmount = loanAmount1;
}
public static int getTerm(){
return term;
}
public void storeTerm(){
Scanner s = new Scanner(System.in);
System.out.println("Enter number of years for the loan: ");
int term1 = s.nextInt();
while(term1 < 10 || term1 > 40){
System.out.println("\tValid Loan Terms are 10-40");
System.out.println("\tPlease re-enter valid number of years: ");
term1 = s.nextInt();
}
term = term1;
}
public static double getInterestRate(){
return interestRate;
}
public void storeInterestRate(){
Scanner s = new Scanner(System.in);
System.out.println("Enter yearly interest rate (Ex: 8.25): ");
double interestRate1 = s.nextDouble();
while(interestRate1 < 2 || interestRate1 > 7){
System.out.println("\tValid Interest Rates are 2% - 7%");
System.out.println("\tPlease re-enter valid yearly interest rate (Ex: 8.25): ");
interestRate1 = s.nextDouble();
}
interestRate = interestRate1;
}
public String getLastName(){
return lastName;
}
public void storeLastName(){
Scanner s = new Scanner(System.in);
System.out.println("Enter customer's Last Name Only: ");
String lastName1 = s.nextLine();
lastName = lastName1;
}
private double calcMonthlyPayment(){
int months = term * 12;
double monthlyInterest = (interestRate / 12 / 100);
double monthlyPay = (loanAmount * monthlyInterest) / (1 - Math.pow(1+ monthlyInterest, -1 * months));
return monthlyPay;
}
private double calcTotalPayment(){
double totalPay = calcMonthlyPayment() * term * 12;
return totalPay;
}
public String getAccountNum(){
return accountNum;
}
public void storeAccountNum(){
StringBuilder accountNum1 = new StringBuilder();
Random rand = new Random();
int accNum = rand.nextInt(9900);
accNum += 100;
accountNum1.append(lastName.substring(0,4));
accountNum1.append(accNum);
accountNum = accountNum1.toString();
}
public String toString(){
DecimalFormat df = new DecimalFormat("#,###.00");
String strMonthlyPayment = ("$" + df.format(calcMonthlyPayment()));
String strTotalPayment = ("$" + df.format(calcTotalPayment()));
return("Account Number: " + accountNum + "\nThe monthly payment is " + strMonthlyPayment + "\nThe total payment is " + strTotalPayment);
}
}
MortgageApp Class
import java.util.*;
public class MortgageApp {
public static void main(String [] args){
Scanner s = new Scanner(System.in);
Mortgage m = new Mortgage();
int size = 10;
Mortgage [] mortgageArray = new Mortgage [size];
int index = 0;
for(index = 0; index < size; index++){
int choice;
System.out.println("\nPlease choose from the following choices below:");
System.out.println("\t1) Promotional Load (preset loan amount, rate, term)");
System.out.println("\t2) Unique Loan (enter in loan values)");
System.out.println("\t3) Quit (Exit the program)");
System.out.println("\n\t Please enter your selection (1-3): ");
choice = s.nextInt();
while(choice < 1 || choice > 3){
System.out.println("\t\tInvalid Choice. Please select 1, 2, or 3: ");
choice = s.nextInt();
}
if(choice == 1){
m.promotional();
String accountNum1 = m.getAccountNum();
mortgageArray[index] = new Mortgage(250000, 20, 3.2, accountNum1);
System.out.println("PROMOTIONAL LOAN...:");
System.out.println(mortgageArray[index].toString());
}
else if(choice == 2){
m.unique();
int loanAmount = m.getLoanAmount();
int term = m.getTerm();
double interestRate = m.getInterestRate();
String accountNum1 = m.getAccountNum();
mortgageArray[index] = new Mortgage(loanAmount, term, interestRate, accountNum1);
System.out.println("UNIQUE LOAN...:");
System.out.println(mortgageArray[index].toString());
}
else if(choice == 3){
System.out.println("\nPROGRAM COMPLETE");
System.out.println("Contents of Array...");
for(int j = 0; j < 10; j++){
if(mortgageArray[j] != null){
System.out.println(mortgageArray[j].toString() + "\n");
}
}
index = 10;
}
}
}
}
The problem is with your loop at the end
for(int j = 0; j < 10; j++){
if(mortgageArray[j] != null){
System.out.println(mortgageArray[1].toString() + "\n");
}
}
It always prints the element at index 1.
Should be
System.out.println(mortgageArray[j].toString() + "\n");
All your fields in the class Mortgage are static.
To fix this, simply remove the static keyword:
private int loanAmount;
private int term;
private double interestRate;
private String accountNum;
private String lastName;
private double monthlyPayment;
private double totalPayment;
Static fields don't belong to an instance, but to the class that gets instantiated. So everytime you call one of your getter-methods, the previous value (of all your instances) will be overriden.
If you are not familiar with classes and objects in Java, this tutorial might be helpfull for you: Understanding Class Members
package homeWork;
public class ShoppingBag {
private int items;
private float totalRetailCost;
private float taxRate;
public ShoppingBag(float taxRate){
this.taxRate = taxRate;
items = 0;
totalRetailCost = 0.0f;
}
// Transformer
public void place(int numItems, float theCost){
items = items += numItems;
totalRetailCost += (numItems * theCost);
}
public int getItems(){
return items;
}
public float getRetailCost(){
return totalRetailCost;
}
public float getTotalCost(){
return totalRetailCost + (1 + taxRate);
}
public String toString(){
String result = "The bag contains " + items + " items";
result += "The retail cost of items is" + totalRetailCost;
result += "The total cost = " + getTotalCost();
return result;
}
}
package homeWork;
import java.util.*;
public class MainClass {
public static void main(String[] args){
Scanner conIn = new Scanner(System.in);
ShoppingBag sb = new ShoppingBag(0.06f);
int count = 0;
float cost = 0.0f;
System.out.print("Enter count (0 to stop):");
count = conIn.nextInt();
while(count != 0){
System.out.print("Enter cost: ");
cost = conIn.nextFloat();
sb.place(count, cost);
System.out.print("Enter count (0 to stop):");
count = conIn.nextInt();
}
}
}
I have tried all that I have found on here to return result after completion of input. Ive done what my book has shown me to do but I am not getting a result. Just a nudge in the right direction would be helpful.
You are no printing the object anywhere. Print the object
System.out.print(sb);
I'm trying to make a unit conversion program but I keep receiving value as infinity. I'm not sure where I need to fix since it's not giving me errors. I only tested oz to ml to make sure I'm doing it correctly but I'm receiving infinity as the answer.
UnitConverter.java:
public class UnitConverter {
final double oz_TO_ml = 29.5735;
final double gal_TO_g = 3.78541;
final double lb_TO_kg = 0.453592;
final double inc_TO_mm = 25.4;//Inc is inches
final double ft_TO_cm = 30.48;
final double mi_TO_km = 1.60934;
double factor;
public UnitConverter(String unit) {
if (unit.equals("oz")) {
factor = oz_TO_ml;
} else if (unit.equals("gal")) {
factor = gal_TO_g;
} else if (unit.equals("lb")) {
factor = lb_TO_kg;
}
}
public double toOz(double amount) {
return (amount * factor);
}
public double fromOz(double amount) {
return (amount / factor);
}
public double toMl(double amount) {
return (amount * factor);
}
public double fromMl(double amount) {
return (amount / factor);
}
}
Calculator.java:
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Convert from: ");
String fromUnit = in.nextLine();
System.out.print("Convert to: ");
String toUnit = in.nextLine();
UnitConverter from = new UnitConverter(fromUnit);
UnitConverter to = new UnitConverter(toUnit);
System.out.print("Value ");
double val = in.nextDouble();
double oz = from.toOz(val);
double converted = to.fromOz(oz);
System.out.println(val + " " + fromUnit + " = " + converted + " " + toUnit);
}
}
Sample input:
Convert from: oz
Convert to: ml
Value 12
Output:
12.0 oz = Infinity ml
Initialize the factor varible with one. A java with default give 0 to primitive double,
class UnitConvertor {
final double oz_TO_ml = 29.5735;
final double gal_TO_g = 3.78541;
final double lb_TO_kg = 0.453592;
final double inc_TO_mm = 25.4;//Inc is inches
final double ft_TO_cm = 30.48;
final double mi_TO_km = 1.60934;
double factor=1;//initialize with 1
But I am still not sure that what is the check you are using if the user input is 'ml'.
public UnitConverter(String unit)
{
if (unit.equals("oz"))
{
factor = oz_TO_ml;
} else if (unit.equals("gal"))
{
factor = gal_TO_g;
} else if (unit.equals("lb"))
{ factor = lb_TO_kg;
}
}
If you pass "ml" the factor will be zero
Your design currently needs two of these but you really only need one as "oz" has everything it needs to do the conversion.
Ignore the the toUnit in your line input code and just use fromUnit
Edit : I'll show you an alternative way to do things, it just supports one convert to show the rough design. Note the method calls are now static because you will only ever need one instance of them
UnitConverter.java
public class UnitConverter
{
private static final double oz_TO_ml = 29.5735;
public static double convert(String fromType, String toType,double amount) throws IllegalArgumentException
{
if (fromType.equals("oz") && toType.equals("ml"))
{
return (amount * oz_TO_ml);
}
else
{
throw new IllegalArgumentException("The combination of converting " + fromType + " to " + toType + " is not supported");
}
}
}
Calculator.java:
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Convert from: ");
String fromUnit = in.nextLine();
System.out.print("Convert to: ");
String toUnit = in.nextLine();
System.out.print("Value ");
double val = in.nextDouble();
System.out.println(val + " " + fromUnit + " = " + UnitConverter.convert(fromUnit,toUnit,val) + " " + toUnit);
}
}
Your UnitConverter class constructor only knows about 3 units: oz, gal, and lb. If you instantiate it with one of those, it will correctly assign the factor and be able to convert units, as seen below:
public UnitConverter(String unit) {
if (unit.equals("oz")) {
factor = oz_TO_ml;
} else if (unit.equals("gal")) {
factor = gal_TO_g;
} else if (unit.equals("lb")) {
factor = lb_TO_kg;
}
}
However, in your Calculator class, you have this line:
UnitConverter from = new UnitConverter(fromUnit);
UnitConverter to = new UnitConverter(toUnit);
If you run your program with your sample input, from is oz and to is ml. But if you instantiate UnitConverter with the unit ml, what does factor get set to? According to your constructor, it is never set, and so it retains its default value of 0.0.
Later, you call this line:
double converted = to.fromOz(oz);
This runs the fromOz method
public double fromOz(double amount) {
return (amount / factor);
}
Which divides by the factor, which is 0.0. This is the source of your Infinity output.
As the other answer says, you don't need to have two UnitConverter objects to perform this calculation. The factor is correct to convert between ounces and millilitres, so this Calculator code is sufficient.
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Convert from: ");
String fromUnit = in.nextLine();
UnitConverter from = new UnitConverter(fromUnit);
System.out.print("Value ");
double val = in.nextDouble();
double result = from.toMl(val);
System.out.println(val + " " + fromUnit + " = " + result + " ml.");
}
}
If you wanted to keep your current calculator code, you would need to add a condition in your UnitConverter constructor for a scalefactor for ml (1.0). However, I think this approach is flawed because what happens, for example, when you try to convert between oz and inches? The conversion makes no sense but your architecture would not prevent it.
can anyone help me with this.
the assignment is to use JOptionPane in arrays. the user will input the length of the array. then at the end of the program, it will display the largest number.
here is what i got so far:
import javax.swing.JOptionPane;
public class array
{
public static void main(String[] args)
{
String L;
int lenght;
L=JOptionPane.showInputDialog(null,"enter lenght: ");
lenght=Integer.parseInt(L);
int[]num = new int[lenght];
for(int counter = 0; counter < lenght ;counter++)
{
JOptionPane.showInputDialog(null,"enter #: "+(counter+0));
int max=num[0];
if (num[counter] > max)
{
max = num[counter];
}
}
JOptionPane.showMessageDialog(null,"the largest number is: " + max);
}
}
then there is this error:
error: cannot find symbol
maxis defined in scope of for loop. So it is not available outside of for.
Define it outside of the for loop and it should work:
public static void main(String[] args) {
String L;
int lenght;
L = JOptionPane.showInputDialog(null, "enter lenght: ");
lenght = Integer.parseInt(L);
int[] num = new int[lenght];
int max=0;
for (int counter = 0; counter < lenght; counter++) {
JOptionPane.showInputDialog(null, "enter #: " + (counter + 0));
max = num[0];
if (num[counter] > max) {
max = num[counter];
}
}
JOptionPane.showMessageDialog(null, "the largest number is: " + max);
}
Update:
You never store the input value to num[counter]
num[counter] = Integer.parseInt(JOptionPane.showInputDialog(null, "enter #: " + (counter + 0)));
package retedunits;
import java.util.Scanner;
public class RentedUnits {
private Integer TOTAL_NUMBER_RENT_UNITS; //Total number of rented units
private Double rentPerUnit; //Rent Per Unit
private Double maintainancePerUnit; //Average Maintainance cost per unit
private Integer currentUnitsRented; //Number of units currently occupied
private Double rentIncreaseFactor; //The level at which people leave
//PROFIT MAX
private Double maxRentForProfit;
private Integer maxUnitsForProfit;
public RentedUnits(Integer totalUnits, Double initalRentPerUnit, Double initialMaintainanceCost, Integer currentRented, Double rentIncreaseFactor){
this.TOTAL_NUMBER_RENT_UNITS = totalUnits;
this.rentPerUnit = initalRentPerUnit;
this.maintainancePerUnit = initialMaintainanceCost;
this.currentUnitsRented = currentRented;
this.rentIncreaseFactor = rentIncreaseFactor;
}
public Double getMaxRentForProfit() {
return maxRentForProfit;
}
public Integer getMaxUnitsForProfit() {
return maxUnitsForProfit;
}
private void increaseRent(Double increasedRent){
//For each $40 increase in rent one unit is vacant.
if(increasedRent > this.rentIncreaseFactor) {
//The number of units that will become vacant is one for every increase of rentIncreaseFactor
int numberVacate = (int) (increasedRent % this.rentIncreaseFactor);
this.currentUnitsRented -= numberVacate;
this.rentPerUnit += increasedRent;
}
else {
this.rentPerUnit += increasedRent;
}
}
private Double calculateProfit(){
//Calculate total rent collected from units that are rented
Double totalRent = this.currentUnitsRented * this.rentPerUnit;
//calculate the maintainanec of all units
Double totalMaintainence = this.TOTAL_NUMBER_RENT_UNITS * this.maintainancePerUnit;
return totalRent - totalMaintainence;
}
public void maximizeProfit(){
/*Keep increasing rent, and let people leave till the total collected
* rent keeps increasing.
*/
/* Assume you begin at all units occupied*/
Double maximumProfit = 0.0;
Double maxProfitRent = 0.0;
Integer maxProfitUnits = 0;
/* Keep increasing rent till all people leave while tracking max profit*/
while(this.currentUnitsRented == 0){
increaseRent(this.rentIncreaseFactor);
if(this.calculateProfit() > maximumProfit){
maximumProfit = this.calculateProfit();
maxProfitRent = this.rentPerUnit;
maxProfitUnits = this.currentUnitsRented;
}
}
this.maxRentForProfit= maxProfitRent;
this.maxUnitsForProfit = maxProfitUnits;
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
RentedUnits rentedUnits = new RentedUnits(50, 600.0, 27.0, 50, 40.0);
rentedUnits.maximizeProfit();
System.out.println(rentedUnits.getMaxUnitsForProfit() + " units needs to be rented at " + rentedUnits.getMaxRentForProfit() + " rent per unit to get maximum profit.");
}
}
I have my code running perfectly, except for my return value for the monthly loan calculator. It keeps on returning Infinity for both my monthly payments and total payments. Please help with the formula. This is a homework. All i need to know is if I am implementing the formula incorrectly. I get the feeling that it is somehow trying to divide over 0 and then returning infinity, but I could be wrong.
public class MyLoan
{
private double amountBorrowed;
private double yearlyRate;
private int years;
public double A;
public double n = years * 12;
public MyLoan(double amt, double rt, int yrs)
{
amountBorrowed = amt;
yearlyRate = rt;
years = yrs;
}
public double getAmountBorrowed()
{
return amountBorrowed;
}
public double getYearlyRate()
{
return yearlyRate;
}
public int getYears()
{
return years;
}
public double monthlyPayment()
{
double i = (yearlyRate / 100) / 12;
A = (amountBorrowed) * (i * Math.pow(1+i, n)) / (Math.pow(1+i, n) -1);
return A;
}
public double totalPayment()
{
return A * (years * 12);
}
public String toString()
{
return "Loan: " + "$" + amountBorrowed + " at " + yearlyRate + " for " + years + " years";
}
public static void main(String[] args)
{
final double RATE15 = 5.75;
final double RATE30 = 6.25;
StdOut.println("***** Welcome to the Loan analyzer! *****");
String ans = "Y";
do {
StdOut.print("\n Enter the principle amount to borrow: ");
double amount = StdIn.readDouble();
MyLoan fifteenYears = new MyLoan(amount, RATE15, 15);
MyLoan thirtyYears = new MyLoan(amount, RATE30, 30);
double amount15 = fifteenYears.monthlyPayment();
double total15 = fifteenYears.totalPayment();
double amount30 = thirtyYears.monthlyPayment();
double total30 = thirtyYears.totalPayment();
StdOut.println("===========ANALYSES==========");
StdOut.println(fifteenYears);
StdOut.println("Monthly payment = " + "$" + amount15);
StdOut.println("Total payment = " + "$" + total15);
StdOut.println("");
StdOut.println("");
StdOut.println(thirtyYears);
StdOut.println("Monthly payment = " + "$" + amount30);
StdOut.println("Total payment = " + "$" + total30);
StdOut.println("=============================");
StdOut.print("\n ** Do you want to continue (y/n)? ");
ans = StdIn.readString();
} while (ans.toUpperCase().equals("Y"));
StdOut.println("\n********** Thank you. Come again! **********");
}
}
You should be debugging this yourself, but I'll give you a hint. What is 1^n (where n is a positive integer)? Where, in your code, are you using this construct?
There is many ways to calculate interest and the most common is just
A = amountBorrowed * (yearlyRate / 100) / 12;