Part B: For Loop Program
Write a program to compute the interest on a bank account. The program will have the following characteristics:
The user will be prompted to input a single line of text containing the deposit amount ($), interest rate (%), and term (in months or years). All items must be separated by whitespace and the input should not be case sensitive. Interest must be compounded monthly. So, some sample (valid) inputs might be:
10000.00 5 36 months
5000.00 4.5 2 years
45000.00 5.0 24 Months
If the user has made an input error, you need to inform them of the error and prompt them to re-enter the information. Primary error conditions are:
Term specified that is not “months” or “years”.
If values for interest rate or term time ≤ 0.
For this program, you must use the FOR loop construct to compute the interest.
You must make sure that interest is computed properly for monthly compounding. If you don’t know what “compound interest” is, Google it. One such site is here.
Once you have verified that the data is properly entered, compute and print out the interest payment on a month by month basis.
At the end of the program, print out the beginning balance, final balance, and the cumulative interest earned. Make sure to clearly label each output.
The code written so far is:
import java.util.Scanner;
public class CompoundInterest {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double principal = 0;
double rate = 0;
double time = 0;
double compoundInterest = 0;
System.out.print("Enter the Principal amount : ");
principal = input.nextDouble();
System.out.print("Enter the Rate : ");
rate = input.nextDouble();
System.out.print("Enter the Time : ");
time = input.nextDouble();
compoundInterest = principal * Math.pow((1 + rate/100), time);
System.out.println("");
System.out.println("The Compound Interest is : "
+ compoundInterest);
}
}
But I don't know how to get input from the user.
You could use the Scanner nextLine() method to read in an entire line of input from the user at once, but then you'd have to tokenize that line and convert each token to the correct data type. It's easier to code and more clear to the user if you ask for one input at a time the way you have it.
Related
I was trying to run my code with a scanner and suddenly it errors when it goes to the 2nd question.
import java.util.Scanner;
public class MyClass {
public static void main(String args[]) {
Scanner stats = new Scanner(System.in);
double base,current;
float bonus;
int level;
System.out.print("Enter the base attack speed: ");
base = stats.nextDouble();
System.out.printf("Enter the bonus attack speed %: " + "%.2f");
bonus = stats.nextFloat();
System.out.println("Enter the level: ");
level = stats.nextInt();
current = (base*1+bonus*level-1) /100;
System.out.print("The character's current speed is: " + current);
}
}
% is what printf (and String.format) use for identifying a placeholder which will be filled in by a parameter provided as second argument.
You therefore have 2 bugs in this code:
The % in attack speed %: is being identified by printf as a placeholder, but you want to print an actual percent symbol. To print that, write 2 percent symbols, which is 'printf-ese' for a single percent symbol: "Enter the bonus attack speed%%: ".
You then add "%.2f" to it which is bizarre, what do you think that does? As written, if you fix the bug as per #1, you immediately get another exception because this requires an argument. The idea is that you can do something like: System.out.printf("The speed of the vehicle in km/h is: %.2f", someValue);. If someValue is, say, 39.8993, that will print the string "The speed of the vehicle in km/h is: 39.90", because you asked for: Print a value as floating point value with max 2 fractional digits. You don't have any input to print there - you're still asking the user, and you can't use this kind of thing to 'format' what the user is supposed to put in. That comes later. So presumably you want to just get rid of that entire "%.2f" thing there.
The user should be able to input data of 5 customers with balances. However this piece of code only works for 1. I initially thought of using a for OR a while loop but I think they will create the display message 5 times.
import java.util.Scanner;
public class Assignment {
public static void main (String [] args) {
Scanner scan = new Scanner (System.in);
Customer c [] = new Customer [5];
Customer hold;
String name; int count = 0;
double totalBalance = 0.0;
System.out.println("For 5 customers enter the name and in the next line the balance"); // displays the message to user
String name = scan.next();
double balance = scan.nextDouble();
c [count++]= new Customer(name,balance);
System.out.println("Search for all customers who have more than $100");
for (int i=0; i<count ; i++){
if (c[i].getBalance()>100)
System.out.println(c[i].getName());
totalBalance += balance;
averageBalance = totalBalance/5;
System.out.println("The average balance is: "+averageBalance);
}
}
System.out.println("For 5 customers enter the name and in the next line the balance"); // displays the message to user
for(int i=0; i<5; i++){
String name = scan.next();
double balance = scan.nextDouble();
c [count++]= new Customer(name,balance);
}
So, in the above code the display message prints 5 times but every time it will be for different customers. For e.g.
Enter 1 customer name and balance
John
20.0
Enter 2 customer name and balance
Jim
10.0
and so on.
I hope this helps. If you ask me you should be using java.util.ArrayList or java.util.LinkedList. These classes come with many features out of the box and you need not code much as in the case of arrays.
You are asking is not a coding problem but just a matter of design.
For what you are doing as per design you can follow below process or similar.
Enter comma separated user names in single line.
Read the line and split the names, now you have x customers detail like name read in a single shot.
Now you have names, repeat 1-2 above for every type of detail just need to be entered comma separated. Try to take one type of detail at a time, i.e. one, line one detail like salary of emp or department.
for pseudo code:
private String[] getDetails(BuffferReader reader){
// read a line at a time, using readline function
// using readed line/console input, split it on comma using split() function and return array of values.
}
I have a compound interest calculator, but when I run the code and input the following numerals when it asks for it:
Principal: 10000
Rate: 0.02
Years:10
and choose "Annual" which is already set up so that if I or a user enters that particular string, the choice variable will automatically become 1 (or the other values already set if I enter the word Quarterly or Monthly). However, I'm supposed to be getting a value of: $12189.94 and am instead getting a value of:10200.0
Where am I doing wrong in my code?
import java.util.Scanner;
import java.lang.Math;
public class CompoundInterest {
public static void main (String [] args)
{
Scanner cool = new Scanner (System.in);
double saving, rate;
int principal, years;
int choice;
System.out.println("Please enter you principal investment:");
/*Print statment prompts user to enter their principal investment*/
principal = cool.nextInt();
System.out.println("Would you like to have a regular investment plan?");
/* Print out statement asks user if they would like to participate in a regular investment plan*/
String question =cool.next();
System.out.println("Please enter the number of years that you wish to invest for:");
/* Print statement prompts user to enter the number of years that they wish to invest for*/
years = cool.nextInt();
System.out.println("Please enter the return rate per year:");
/* Print statement prompts user to enter the return rate per year*/
rate = cool.nextDouble();
System.out.println("What type of investment plan would you prefer (Annual, Quarterly, or Monthly)?");
String quest =cool.next();
if ("Annual".equalsIgnoreCase(quest))
{ choice =1;
}
else if ("Quarterly".equalsIgnoreCase(quest)){
choice = 4;
}
else if ("Monthly".equalsIgnoreCase(quest)){
choice = 12;
}
else {
choice = 0;
System.out.println("Please choose a investment plan or speak to a financial advisor.");
}
saving = principal*(1+(rate/choice))*Math.pow(choice,years);
System.out.println(saving);
Thank you to everyone for providing suggestions. It just seemed that I needed to use:
saving = principal * Math.pow(1+(double) (rate/ (choice)), choice * years);
In order for my equation to work as it seems my equation wasn't properly taking into consideration my integer values as saving is categorized as a double.
Your formula for calculating interest is incorrect. It should be:
saving = principal*Math.pow(1+(rate/choice), choice*years);
See the correct formula here: https://en.wikipedia.org/wiki/Compound_interest#Periodic_compounding
I'm suppose to enter 2 numbers, one int that is the amount to withdraw and one double which is the balance (with a space between them). Since every withdraw charges a fee of 0.5, balance must be a double. And thats what must be printed.
I get error at nextDouble, why? I have just 1 month coding, I thought this was going to be a piece of cake, I think BASIC syntax ruined me 30 years ago :(
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
//init variables
int amount;
double balance;
//insert amount and balance
Scanner input = new Scanner (System.in);
amount = input.nextInt();
balance = input.nextDouble();
//reduce amount+fee from balance
balance=balance-(amount + 0.50);
//print new balance
System.out.print(balance);
input.close();
}
}
It is dependant on Locale, try to use comma instead of a dot or vice versa.
Ex: 1,5 instead of 1.5
You can check, if there is some int or double to read.
And you have to use , or . depending on the country, you are.
If you need it country independent, read it as string and parse then (see below)
A solotion would be to read the line as a string and parse it then to int and double.
Checking if double is available:
input.hasNextDouble();
Read as String:
String line = input.nextLine();
String[] sl = line.split(" ");
amount = Integer.parseInt(sl[0]);
balance = Double.parseDouble(sl[1]); //solve the problem with . and ,
You also could check if there are enough inputs.
I'm trying to create a program in java that should calculate the monthly payment and total interest paid on financing for any given purchase. The application should also allow the user to compare the differences between two different payment plans.
What I have
Scanner scan = new Scanner(System.in);
System.out.println("Enter the total cost of the purchase:");
float tPurchase = scan.nextFloat();
System.out.println("Enter your first down payment:");
float Paymentone = scan.nextFloat();
System.out.println("Enter your second down payment: ");
float Paymenttwo = scan.nextFloat();
System.out.println("Enter first lenght of time to pay");
float paylenght = scan.nextFloat();
System.out.println("Enter second length of time to pay:");
float paylength2 = scan.nextFloat();
System.out.println("Enter APR:");
My question is how do I get the program to scan the next number as a percentage. For instance, total purchase 10,000, down payment 3,000, second down 5,000, APR one 1% for three years and APR two 2% for 5 years. No need to tell me how to make it calculate, just how to make it scan as a percentage.
There is no different with how to scan the next number as a percentage and what you have done above.
Perhaps the only thing that you need to change is:
System.out.println("Enter the percentage:");
And you may retrieve the input by either:
float percentage = scan.nextFloat(); //or
int percentage = scan.nextInt();
Or if you want user to include % in their input then you might want to do:
String strPercentage = scan.nextLine();
float percentage = Float.parseFloat(strPercentage.substring(0,strPercentage.length()-1));
Of course you need to validate the user input to match you desired value first.
It depends on how you want the behaviour of your application to be. Will it accept aor to be in the form of xx %, x.xx or only xx?
Then this code will deal with all those three cases:
System.out.println("Enter APR:");
String aprTemp = scan.next();
int apr;
if (aprTemp.contains("%")) {
String aprStr = aprTemp.substring(0, aprTemp.indexOf("%"));
apr=Integer.parseInt(aprTemp);
}else if(aprTemp.matches("[0-9]+")){ // regex for number
apr=Integer.parseInt(aprTemp);
}else if(aprTemp.matches(""^([+-]?\\d*\\.?\\d*)$""){ // regex for float
float aprFloat=Float.parseFloat(aprTemp);
}