I'm just starting to learn my first programming language as of yesterday, so I'm writing simple test programs from my java book.
What I'm attempting to do is to have a user enter a static monthly investment and how many months they will be saving for, then display their total savings after that period of time.
when I compile the program it says that in system.out.println at the end of the program that total has not been initialized. I have tried initializing total in just the loop but I figured that would put the scope of it in the loop So I tried initializing it at the top and figured it runs through the loop until the condition is met but doesn't go back to the top of the program to put the value back in so I make another variable at the end of the loop to hold the total at the end of the loop. What's Wrong with my logic
thank you for the help!
import java.util.Scanner;
public class CompoundInterestSteadyRate {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
double monthlyInterestRate = (1 + 0.00417);
System.out.println("please enter amount saved each mounth");
double amountSavedMonthly = input.nextDouble();
System.out.println("please enter amount of months you will be saving for");
int amountOfMonthsSaved = input.nextInt();
int monthCountDown = amountOfMonthsSaved;
double totalAmount;
double addMonths;
double intitalAmount = 0;
while (monthCountDown > 0){
addMonths = amountSavedMonthly * monthlyInterestRate + intitalAmount;
intitalAmount = addMonths;
totalAmount = intitalAmount;
}
double total = totalAmount;
System.out.println("your total after " + " " + amountOfMonthsSaved + " " + "months is:" + " " + "$" + total);
}
}
thanks everyone for the help it now compiles however it seems when going through the math it doesn't take in account the first month of savings for example if I do $100 each month its total at the end is %502.08 which I don't believe is right
import java.util.Scanner;
public class CompoundInterestSteadyRate {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
double monthlyInterestRate = (1 + 0.00417);
System.out.println("please enter amount saved each mounth");
double amountSavedMonthly = input.nextDouble();
System.out.println("please enter amount of months you will be saving for");
int amountOfMonthsSaved = input.nextInt();
int monthCountDown = amountOfMonthsSaved;
double totalAmount = 0;
double addMonths;
double intitalAmount = 0;
while (monthCountDown > 1){
addMonths = amountSavedMonthly * monthlyInterestRate + intitalAmount;
intitalAmount = addMonths;
totalAmount = intitalAmount;
monthCountDown = monthCountDown - 1;
}
double total = totalAmount;
System.out.println("your total after " + " " + amountOfMonthsSaved + " " + "months is:" + " " + "$" + total);
set totalAmount = 0,that will instialize it, let me know if this fixes the problem
when you declare it declare it like this double totalAmount = 0;
try 2 steps:
double totalAmount; ==> double totalAmount = 0;
while (monthCountDown > 0); ==> while (monthCountDown-- > 0);
Hava a nice day, my friend.
This problem is a little intricate although the compiler (javac program) provides following helpful message:
Compound.java:33: error: variable totalAmount might not have been
initialized double total = totalAmount;
What could be happening you may wonder. The easy answer is to go to line 20 in your program and initialize the value of totalAmount to 0. Then your program would compile.
The reason the compiler does that is rather complicated, but you can reason about it this way:
What if, just what if the while loop did not get run even once (as written, in your program, opposite is happening as you will soon figure out that you are forgetting something about the loop variable)? Then Java would execute the (next) statement double total = totalAmount; and the way this assignment statement is executed is roughly like this:
read the variable on the right side of =, that is totalAmount in a temporary location
transfer the contents of that location to the memory for the variable on the left side of =, i.e. total.
Now, Java does not like to read a local variable's (such as totalAmount) value that is never written to because it may contain some garbage value. When you initialize it with a value like 0, this problem goes away.
First of all there is no need of using intitalAmount and totalAmount. Because each time you are inserting same values to them. Secondly if you make
monthCountdown > 1
then it will count a month less. Because suppose you are counting for 6 months. Now for monthCountdown > 1 the loop will iterate for 5 times and calculate interest for 5 times. Which I believe is not the logic you want to implement.
So it should be,
monthCountdown > 0
Lastly your mathematical logic is not correct because each time you are calculating the interest on the monthly value and adding it with the previous balance. But it should be like each time interest should be calculated on the total current balance.
while (monthCountDown > 0){
totalAmount = ( amountSavedMonthly + totalAmount ) * monthlyInterestRate;
}
Please let me know if any concern.
First of all, it isn't necessarily the case that totalAmount will not be initialized. However, depending on the user input, it is POSSIBLE that totalAmount will not have been initialized, which will then throw an exception when the program attempts to assign the value of totalAmount to total. To avoid this, you need to ensure that totalAmount gets initialized, which is easy to do. When you declare totalAmount, simply assign 0 as its value.
You also have a problem with your while loop. Because the value of monthCountDown is never changed within the loop, there is no way for the condition monthCountDown > 0 to become false. I'm assuming you intended for monthCountDown to be reduced by 1 each time the loop is run, so you should include monthCountDown--; within the loop to prevent it from becoming an infinite loop.
Initialize totalAmount to 0...
Make in while condition greater than 1..
cricket-007 is right about initializing totalamount = 0; But it looks like your while loop keeps going. Try this!
changed your arrow key from > to <, on the while loop
import java.util.Scanner;
public class CompoundInterestSteadyRate {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double monthlyInterestRate = (1 + 0.00417);
System.out.println("please enter amount saved each mounth");
double amountSavedMonthly = input.nextDouble();
System.out.println("please enter amount of months you will be saving for");
int amountOfMonthsSaved = input.nextInt();
int monthCountDown = amountOfMonthsSaved;
double totalAmount =0;
double addMonths;
double intitalAmount = 0;
while (monthCountDown < 0) {
addMonths = amountSavedMonthly * monthlyInterestRate + intitalAmount;
intitalAmount = addMonths;
totalAmount = intitalAmount;
}
double total = totalAmount;
System.out.println("your total after " + " " + amountOfMonthsSaved + " " + "months is:" + " " + "$" + total);
}
}
Related
I'm sorry, I know this question is probably asked a million different times every day, but I truly can't find the answer I'm looking for. I'm a beginner in Java (I'm in college and learning a bunch of new languages), and my while loop is printing out the same thing every time.
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("What is the loan amount? ");
int amount = scanner.nextInt();
int x = 1;
//your code goes here
while (x < 6){
System.out.println("Month " +x+ ":");
int percent = (amount / 10);
System.out.println("Payment: 10 percent of " +amount+ " = " +percent);
int rAmt = amount - percent;
System.out.println("Remaining amount: " +rAmt);
x++;
}
}
}
So the issue is that you never actually change amount after doing your calculations inside the while loop. What I think you want to do, is to set amount = rAmt;, which would produce the following code. This will cause the amount to be decreased by 10% each iteration, and this new value carried forward.
...
//your code goes here
while (x < 6){
System.out.println("Month " +x+ ":");
int percent = (amount / 10);
System.out.println("Payment: 10 percent of " +amount+ " = " +percent);
int rAmt = amount - percent;
System.out.println("Remaining amount: " +rAmt);
amount = rAmt;
x++;
}
...
I am in the process of writing code that asks the user for their name, how many jobs they have, and the income of those jobs. Then the code finds the highest and lowest paying incomes, and the average of the jobs they entered.
Im having issues with the highest and lowest paying portion, along with finding the average, while still maintaining what the user entered in order to recite it later.
Ex:
Inputs: 10000 30000 50000
"Hello Audrey. You have had 3 jobs. The highest paying job paid $50000. The lowest paying job paid $10000. The average pay for the jobs entered is $30000
**** heres the code I have edited, but it is not running properly. I believe it has to do with int and double. Im not sure which code should be double and which ones should be int.****
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class JobIncome {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner (System.in);
System.out.println("What is your first name? ");
String firstName = input.nextLine();
Scanner scan = new Scanner (System.in);
System.out.println("How many jobs have you had? ");
int jobNum = scan.nextInt();
//Declarations
int total = 0;
int average = 0;
//for loop asks for the incomes of the user's previous
//jobs and stores them into an array
int arrayOfIncomes[] = new int[jobNum];
for(int i = 1; i <= arrayOfIncomes.length; i++){
System.out.println("Enter the income of job #" + i + " : ");
arrayOfIncomes[i] = scan.nextInt();
total = total + arrayOfIncomes[i];
}
average = total/jobNum;
//Start of the code that will find the min and max
int min = arrayOfIncomes[0];
int max = arrayOfIncomes[0];
for (int i = 1; i < arrayOfIncomes.length; i++) {
if (arrayOfIncomes[i] > max) {
max = arrayOfIncomes[i];
}
}
for (int i = 1; i < arrayOfIncomes.length; i++) {
if (arrayOfIncomes[i] < min) {
min = arrayOfIncomes[i];
}
}
//Print statement that gives the user all their information
System.out.println("Hello, " + firstName + ". You have had" + jobNum +
"jobs. The highest paying job paid $" + max +
". The lowest paying job paid $" + min +
". The average pay for the " + jobNum + "jobs entered is $" + average + ".");
//Prompt asking the user if they would like to print their info into a text file
System.out.println("Would you like to output your information into a text file, yes or no? ");
String yesNo = input.nextLine();
if(yesNo.equals("yes")){
System.out.println("");
} else {
System.out.println("Goodbye.");
}
//Output code
Scanner console = new Scanner(System.in);
System.out.print("Your output file: ");
String outputFileName = console.next();
PrintWriter out = new PrintWriter(outputFileName);
//This code prints the information into the output text file
out.print("Hello, " + firstName + ". You have had" + jobNum +
"jobs. The highest paying job paid $" + max +
". The lowest paying job paid $" + min +
". The average pay for the " + jobNum + "jobs entered is $" + average + ".");
out.close();
}
Fix the code by instantiating an array, jobIncomes with the length equivalent to the number of jobs. You could keep a running average, but you would lose precision when rounding. You will also need to instantiate three integer variables: total, max and min, each at zero.
For every iteration of the loop, you should add the following code:
jobIncomes[i-1]=s.nextInt();
if (jobIncomes[i-1]<min)
{ min=jobIncomes[i-1];}
if (jobIncomes[i-1]>max
{max=jobIncomes[i-1];}
total+=jobIncomes[i-1];
When you print the average, you can cast the formula average = total/jobNum. You might also want to change the array values to read from 0 to jobNum-1, if you want to index simply by i in the if statements.
Create an int variable sum. Add the sum as you get input from the user then divide the sum with the variable jobNum while casting at least one variable to double.
Example:
double ave = (double) sum / jobNum;
Im new to java and practising my coding, how would I write some Junit tests for this code without changing it? I wanted to write some Junits to see if the output is correct. Could someone provide one such example?
Any help is greatly appreciated.
package returnOnInvestment;
import java.util.Scanner;
/**
This program compares CD /Investment plans input by the year
broken down by the requirements below:
This program creates a table of compound interest investment growth over time
Broken down by: a) year b) balance at end of year
Finance formula of A= P(1+ r/n)^n*t is used:
A = Future Value | P = Initial Investment
r = annual interest rate |n = times interest is compounded/year
t = years invested
*/
public class BestInvesment
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String bestBankName = "";
double bestGrowth = 0;
boolean done = false;
while(!done)
{
System.out.print("Plan name (one word, Q to quit): ");
String bankName = in.next();
if (bankName.equals("Q"))
{
done = true;
}
else
{
System.out.print("Please enter your principal investment: ");
final double PRINCIPAL_INVESTMENT = in.nextDouble();
System.out.print("Please enter the annual interest rate: ");
double iRate = in.nextDouble();
System.out.print("Please enter number of times interest is compounded per year: ");
final double INCREMENT = 1;//in.nextDouble();
System.out.print("Enter number of years: ");
int nyears = in.nextInt();
iRate = iRate/100; System.out.println("iRate:" + iRate);
//Print the table of balances for each year
for (int year = 1; year <= nyears; year++)
{
double MULTIPLIER = INCREMENT * year;
System.out.println("Multiplier: " + MULTIPLIER); // I've included this print statement to show that the multiplier changes with each passing year
double interest = 1 + (iRate/INCREMENT);
double balance = PRINCIPAL_INVESTMENT;
double growth = balance * Math.pow(interest, MULTIPLIER);
growth = growth - PRINCIPAL_INVESTMENT;
balance = balance + growth;
System.out.printf("Year: %2d Interest Earned: $%.2f\t Ending Balance: $%.2f\n", year, growth, balance);
if (bestBankName.equals("") || bestGrowth > growth) // || bestBankName > growth
{
bestBankName = bankName; // bestBankName = bankName
bestGrowth = growth; // mostGrow = growth
}
System.out.println("Earning with this option: " + growth);
}
}
}
System.out.println("Best Growth: " + bestBankName);
System.out.println("Amount Earned: " + bestGrowth);
}
}
As it is, this code is very difficult to test, which it is a symptom of some design smells.
One thing to realize is that you are severely violating the Single Responsibility Principle.
Your code which is just one blob is doing the following things:
printing stuff to console
getting input from the user
doing some calculation
coordinating all this
Since this is in the realm of practicing, I would heavily refactor the code into separate classes. Those then should be easily testable, especially the one doing the calculation, since it will have just some simple methods where you can pass some values as arguments, and check the results
For testing the input and output classes note that you can change System.in and System.out to point to your own implementations, so you can create those to facilitate testing. You might want to look into a mocking framework for this (e.g. Mockito) but it is perfectly possible without such framework.
I have been working on a project for my course. It's a simple salary calculator, which I have figured out fairly easily and it functions flawlessly. It also takes into consideration benchmarks for commission. I have completed choped on the last part, however. I cannot get it to function. It either loops indefinitely, or it generates static numbers under the "Total Compensation" column (they should be dynamic based on commission etc).
Bob makes $85,000 a year.
He gets no bonus/commission if he sells less than $120,000
He gets 15% commission if his sales for the year are >= $120,000
He gets an additional 2% for every $150k in sales (150k, 300k, 450k
etc)
User inputs a sales number (example: $300,000).
Program calculates BaseSalary + ($300,000 * .15) + ($300,000 * .02)
Potential Sales on the left and then Total Compensation on the right side
200,000 ----------------------> (Calculated)
220,000 ----------------------> (Calculated)
240,000 ----------------------> (Calculated)
260,000 ----------------------> (Calculated)
280,000 ----------------------> (Calculated)
300,000 ----------------------> (Calculated)
//Variables defined here
double Sales = input.nextDouble();
double TotalCompensation;
int Commission;
double CommissionRate;
double AcceleratedCommissionRate;
int BaseSalary;
double TargetSales;
double Accelerator;
double AcceleratorGoal;
double AcceleratedCommission;
// Mathematical Operations
Accelerator = 0.80;
TargetSales = 150000;
CommissionRate = 0.15;
AcceleratedCommissionRate = ((CommissionRate) * (2.0));
BaseSalary = 85000;
Commission = (int) (Sales * CommissionRate);
AcceleratedCommission = (double) (Sales * AcceleratedCommissionRate);
AcceleratorGoal = (double) 120000;
// If Else Logic Flow
if(Sales < AcceleratorGoal)
{
TotalCompensation = BaseSalary;
System.out.print("\nCommission Goal HAS NOT been met");
System.out.println("\nTotal annual compensaton is: ");
System.out.println(numberFormat.format(TotalCompensation));
}
else if(Sales < TargetSales)
{
TotalCompensation = BaseSalary + Commission;
System.out.print("\nCommission Goal HAS been met");
System.out.println("\nTotal annual compensaton is: ");
System.out.println(numberFormat.format(TotalCompensation));
}
else if(Sales >= TargetSales)
{
TotalCompensation = BaseSalary + AcceleratedCommission;
System.out.print("\nAccelerator Goal HAS been met");
System.out.println("\nTotal annual compensaton is: ");
System.out.println(numberFormat.format(TotalCompensation));
}
// Potential Commission Structure Table
double PotentialSales;
double EndLoop = (Sales * 1.5);
int Increment = 20000;
System.out.println("\nPotential Sales\t\tTotal Compensation");
for (PotentialSales = Sales; PotentialSales < EndLoop;
PotentialSales = PotentialSales += Increment)
{
do
{
String output = numberFormat.format(PotentialSales) + "\t\t"
+ numberFormat.format(BaseSalary);
System.out.println(output);
}
while(PotentialSales < AcceleratorGoal);
do
{
String output = numberFormat.format(PotentialSales) + "\t\t"
+ numberFormat.format(Commission + BaseSalary);
System.out.println(output);
}
while(PotentialSales >= AcceleratorGoal && PotentialSales < TargetSales);
do
{
String output = numberFormat.format(PotentialSales) + "\t\t"
+ numberFormat.format(AcceleratedCommission + BaseSalary);
System.out.println(output);
}
while(PotentialSales >= TargetSales);
}
Any suggestions or tips whatsoever would be a lifesaver.
This code will iterate until expression (PotentialSales < AcceleratorGoal) is false. As you are not updating the value of PotentialSales & AcceleratorGoal in the body of do{..body..}while(expression), it will iterate indefinitely if (PotentialSales < AcceleratorGoal) is true at first place, otherwise it will get executed once and will go to the next statement after the while condition.
Code
do{
String output = numberFormat.format(PotentialSales) + "\t\t" + numberFormat.format(BaseSalary);
System.out.println(output);
}while(PotentialSales < AcceleratorGoal);
You might want to update the PotentialSales or AcceleratorGoal Value inside the body of do while loop or change condition w.r.t output variable.
Same goes for next two do..while loops.
Your do while loop repeats infinitely because,you are not updating the value of PotentialSales in do while loop
To understand the problem,check the following code
int accelerationsales=5;
for(int potentialsales=0;potentialsales<5;potentialsales=potentialsales+=1) {
do {
System.out.println("Hello");
} while(potentialsales<accelerationsales);
}
Run this sample code,you will understand the problem.
My program is nearly done except for one problem. I'm having an out of scope problem with the for loop. The goal of the program is to compound monthly interest for a user inputted amount & term.
An example of output at $5000 principal with 5% interest for 3 years would be:
Month: Interest: Principal:
1 $20.83 $5020.83
2 $20.92 $5041.75
etc etc etc
Starting Balance = $ 5000.00 // having problem outputting these w/ for-loop
Final Account Balance = $ 5807.36 // System.out.print keeps repeating multiple times
Total Interest Paid = $ 807.36 // but i can't use variables outside of loop
My problem is that during my for loop, I keep outputting Starting Balance, Final Balance and Total Interest every time the program goes through the loop. but if I try to use the variables outside the loop it goes out of scope and if I try to declare variables outside of the loop I can't use them inside the loop because it's already been declared in the constructor.
Can anyone give me some hints or advice?
My code:
public class Calculator
{
public Calculator()
{
Scanner input = new Scanner(System.in);
boolean error = false;
while (!error){
System.out.print("Please input the following: principal, interest rate, term >> ");
double principal = input.nextDouble();
double interest_rate = input.nextDouble();
int term = input.nextInt();
String Month = input.next();
char dollar_sym = 36;
if (interest_rate <= 0 || term <= 0 || principal <= 0) // input validation
{
System.out.println("The term, interest rate and principal must be greater
than zero");
continue;
}
if (!Month.equals("month")) // input validation
{
System.out.println("Please input month after term");
continue;
}
System.out.println("Month: " + " Interest: " + "Principal: ");
if (Month.equals("month"))
{
for (int month = 1; month <= term; month++)
{
double interest = (principal * interest_rate / 100) / 12;
principal = principal + interest;
System.out.printf("%4d %c%5.2f %c%5.2f\n", month,
dollar_sym, interest, dollar_sym, principal );
double start_principal = principal - interest; // problem
double final_principal = principal; // problem
double total_interest = interest * interest_rate; // problem
System.out.println(" Starting balance = " + start_principal ); // problem
System.out.println("Final account balance = " + final_principal ); // problem
System.out.println("Total Interest Paid = " + total_interest); // problem
}
}
}
}
}
Declare them before the loop begins, so they will exist inside the loop and after it:
double start_principal = 0;
double final_principal = 0;
double total_interest = 0;
Scanner input = new Scanner(System.in);
boolean error = false;
while (!error) {
// ...
}
// ...
In my answer, I am assuming that when you say goes out of scope, you mean that you get a compile time error. (note, it would make the answer easier to address if you provided the error message and the line that is causing the error message).
The scope of a variable refers to where the variable is accessible. For example, if you declare a variable inside of an if statement, the scope is that if statement. Some example code:
public void updateStatus(){
Boolean shouldCheckStatus = true;//this variable is declared inside of the updateStatus method, so that is the scope of the variable
if(shouldCheckStatus == true){
Int hitCounter = 0;//this variable is declared inside of the if statement, so it is only accessible inside of the if statement
//do some work
if(hitCounter > 100){
self.registerHits(hitCounter);//hitCounter is still accessible here, because it is still inside of the if statement
}
else{
shouldCheckStatus = false;
}
}//close the if statement and so close the scope...
//the hitCounter variable is no longer in scope, because we are no longer in the if statement
//but shouldCheckStatus is still in scope, because we are still in the method
if(shouldCheckStatus == true){
self.callAnotherMethod();
}
}
So in your problem, you need to declare your variable above where you want to use it, inside of the scope that you want to use it. And then not declare it again. So declare before the loop.