I was going through a code used to calculate investments until it has doubled and I received an infinite loop that I can't seem to solve. Can anyone figure out why this is giving me an infinite loop? I've gone through myself but I can't seem to find the problem. The "period" referred is how many times per year the interest is compounded.
double account = 0; //declares the variables to be used
double base = 0;
double interest = 0;
double rate = 0;
double result = 0;
double times = 0;
int years = 0;
int j;
System.out.println("This is a program that calculates interest.");
Scanner kbReader = new Scanner(System.in); //enters in all data
System.out.print("Enter account balance: ");
account = kbReader.nextDouble();
System.out.print("Enter interest rate (as decimal): ");
rate = kbReader.nextDouble();
System.out.println(" " + "Years to double" + " " + "Ending balance");
base = account;
result = account;
for (j=0; j<3; j++){
System.out.print("Enter period: ");
times = kbReader.nextDouble();
while (account < base*2){
interest = account * rate / times;
account = interest + base;
years++;
}
account = (((int)(account * 100))/100.0);
//results
System.out.print(" " + i + " " + account + "\n");
account = result;
}
The code should ask for three "periods", or three different times the entered data is compounded per year (ex annually, monthly, daily etc.)
Thanks a lot!
Instead of doing
account =interest +base
You should have
account = interest +account
You should add some sanity checking. Either check if all the numbers will result in a finite number of loops (account and rate != 0, maybe some other stuff), or more simply, break if you've looped more times than would be reasonable (say 1000 for instance). My guess is that rate is 0 resulting in no increase in account, therefore it will loop forever.
You have a calculation error:
account = interest + base;
Presumably this should be:
account = account + interest;
Also, are you sure you want to have the int cast?
account = (((int)(account * 100))/100.0);
You're throwing away the values smaller than 1 cent apparently. However, if the interest is too small you will not get any change.
The reason it may loop forever is that the double calculation of account is effectively truncated by casting to int, so it may never change if rate is too small and the new value of account isn't made larger by at least 0.005.
Related
My problem statement is:
Write a program that creates two instances of the generic class
LinkedList.
The first instance is stadiumNames and will hold items of
type String.
The second instance is gameRevenue and will hold items of
type Double.
Within a loop, read data for the ball games played during
a season.
The data for a game consists of a stadium name and the
amount of money made for that game.
Add the game data to stadiumNames and gameRevenue.
Since more than one game could be played at a particular stadium, stadiumNames might have duplicate entries.
After reading the data for all of the games, read a stadium name and display the total amount of money made for all the games at that stadium.
I'm trying to get each input from the user and then add each input together and get its sum, it seems to get it right at first, but then it prints another totally different amount. Why is that? Any help appreciated.
Each input the stadiumName and gameRevenue were added to a linkedList.
Note that I already wrote both linked lists but it won't allow me to post a big chunk of code. Thank you.
boolean Data = true;
while (Data) {
stadiumNames.add(name);
gameRevenue.add(rev);
System.out.println("Do you want another game? ");
String yesorno = scan.next();
if (yesorno.equals("No"))
break;
else {
if (yesorno.equals("yes"))
System.out.println("Enter stadium name: ");
name = scan.next();
System.out.println("Enter amount of money for the game: ");
rev = scan.nextDouble();
for (int i = 0; i < stadiumNames.size(); i++) {
if (stadiumNames.get(i).equals(name)) {
rev += gameRevenue.get(i);
System.out.println("The total amount of money for " + name + " is " + rev);
}
}
}
}
If you want to print running total while user is entering the data, total should be reset for each calculation.
while (true) {
System.out.println("Do you want another game? ");
String yesorno = scan.next();
if (yesorno.equals("No"))
break; // else not needed
System.out.println("Enter stadium name: ");
name = scan.next();
System.out.println("Enter amount of money for the game: ");
rev = scan.nextDouble();
stadiumNames.add(name);
gameRevenue.add(rev);
double total = 0.0;
// recalculating the total for the last stadium
for (int i = 0; i < stadiumNames.size(); i++) {
if (stadiumNames.get(i).equals(name)) {
total += gameRevenue.get(i);
}
}
System.out.println("The total amount of money for " + name + " is " + total);
}
However, it may be needed to calculate the totals for multiple different stadiums and a map needs to be created and filled for this after the while loop.
It is convenient to use Map::merge function to accumulate the totals per stadium name.
Map<String, Double> totals = new LinkedHashMap<>();
for (int i = 0; i < stadiumNames.size(); i++) {
totals.merge(stadiumNames.get(i), gameRevenue.get(i), Double::sum);
}
totals.forEach((stad, sum) -> System.out.println("The total amount of money for " + stad + " is " + sum));
Aside comment: it is not recommended to use double for financial calculations because floating point maths is not precise.
My assignment is to create a calculator that can calculate how much is left on a giftcard after purchasing an item, but also making sure not to go over 6 items, or $225, whichever comes first. I know I need another method to do a calculation but i'm not sure what to put in it. This is what I have so far:
I know I will need a for loop for the counter for the items, but I'm really stuck. I posted the actual assignment to give background.
For your birthday, your rich aunt & uncle give you a $225 gift card to
the local mall. They will go shopping with you and will help carry out
your items. The most that each of you can carry is one item in each
hand. Thus, you may purchase a maximum of six items. You will have a
tracker device that computes the number of items you purchase as well
as the amount of money you have spent. After you choose each item, the
tracker prompts you for the price, and then displays the amount of
money you have spent. Then it displays the number of items you may
still choose and the balance on the gift card. The program will not
terminate until you reach 6 items or $225, whichever comes first. The
tracker then will list the total spent & the number of items as well
as the balance on the gift card.
Required:
validate that negative
prices are not entered and that you can’t spend more than the balance
on the gift card. Give the user as many opportunities as needed to
enter a price above 0 or below 225. User should be able to purchase
items costing between one penny and $225, inclusive.
all dollar
amounts should be formatted for currency using the NumberFormat class.
Include at least 1 method in your program.
Be sure to create test cases for all options:
spend the entire dollar amount on fewer than 6 items
purchase 6 items totaling less than the entire dollar amount
spend the entire dollar amount on exactly 6 items
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double priceItem = 0, totalPrice = 225, currentPrice = 0;
int numItem;
System.out.println("Happy birthday from Auntie and Uncle! \nYou may purchase up to"
+ " 6 items with this gift card of $225.");
for (numItem = 1; numItem <= 6; numItem++) {
System.out.println("Enter the price for item #" + numItem + ": ");
priceItem = input.nextDouble();
while (numItem <= 6 && totalPrice <= 225) {
totalPrice = currentPrice - priceItem;
System.out.println("You may buy this item. You have spent ");
if (currentPrice > totalPrice) {
System.out.println("Item is too expensive. Balance on gift card is " + currentPrice);
}
}
}
}
Whenever I have tried to make a while loop, it is an infinite loop and again I'm not sure which calculation to put in to get it to break.
I don't want to give you the answer as it is something you should solve yourself but I will give a few pointers.
Your use of a while loop here is incorrect, do you really need a while loop?
if(totalPrice <= 225) break;
Perhaps look into the break statement to exit the loop when a certain condition is met, that why you can ensure there are 6 items or less and it is not over 225.
You also need to handle an entry of 0 as it is a penny minimum and you cannot allow them to exceed 225.
priceItem = input.nextDouble();
while(priceItem < 0.01 || priceItem > 225){
System.out.println("Item Price cannot be 0 or greater than 225, please...");
priceItem = input.nextDouble();
}
You also can't allow a value that exceeds the remaining balance, I will let you try and figure out how to do that yourself. What you have done so far isn't bad you just need to break it down a bit more.
This is how I would construct it:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double balance = 225.0;
double itemPrice = 0;
int boughtItems = 0;
int maxItems = 6;
System.out.println("Happy birthday from Auntie and Uncle! \nYou may purchase up to"
+ " 6 items with this gift card of $225.");
while(boughtItems < maxItems && balance > 0) {
System.out.print("You have " + balance + "$ on your giftcard. \nEnter the price for item #" + (boughtItems + 1) + ": ");
itemPrice = input.nextDouble();
if(balance - itemPrice > 0.0) {
balance -= itemPrice;
System.out.println("You have bought the Item!\n\n\nYou can carry " + (maxItems - boughtItems - 1) + " more things!\n");
boughtItems++;
} else {
if(balance - itemPrice == 0) {
balance -= itemPrice;
boughtItems++;
System.out.println("\nYou have spent all your money.");
}
else {
System.out.println("You dont have enough money for this Item!\n\n\n");
}
}
}
System.out.println("You bought " + boughtItems + " item/s. " + "Have fun with the stuff!");
}
You can write a buy(double balance, double price) method for example, so you fill in the assignment requirements.
And of course you need to do the rest of the stuff like the number-formatting.
In the while loop, you are doing wrong assignment, that’s why infinite loop.
Assign currentPrice is equal to totalPrice - price for item purchased.
Can anyone help me here?? I have compiled and successfully run a program using Java which takes user inputs from an "inputdialog" box and displays this information back in the console along with a simple mathematical formula. The problem I cannot seem to overcome is when the data is input the user has an option to enter another set of the same data type but I need the console to register this as a second input. This is how far I am currently with the section of code and my ideas on how to make this work using an array but I have been informed that saving/storing the data as an object might be a better option?
private void enterCar()
{
String carInfo;
int carHours;
int i = 0;
int[] carNumb = new int[20];
double fee = Double.parseDouble("7.50");
double sum = 0;
final int MAX = 12;
{
carInfo = JOptionPane.showInputDialog("Please enter the license plate of the car");
carHours = Integer.parseInt(JOptionPane.showInputDialog("Enter the number of hours the car was parked (1-12):"));
System.out.printf("\n");
System.out.printf("Details for car "+carNumb+" entered:\n");
System.out.printf("License plate Hours Fee:\n");
System.out.printf(""+carInfo+" "+carHours+" $");
if (carHours == 1)
System.out.printf("%3.2f",fee*(carHours));
else if (carNum == 2)
System.out.printf("%3.2f",fee+4.50);
else if (carHours >= 3)
System.out.printf("%3.2f",3+(carHours*4.50));
System.out.printf("\n\n");
}
}
When I compile and run the console I get the line "Details for car [I#6659c656 entered". This line does change to something like "[I#7665c575" the next time I activate the option so I can assume that I may need to assign a value to the number differently?
I have tried the option that is show in the code provided as well as trying to activate a list using (1, 2, 3, ect) but this also just outputs that random line of numbers and letters.
I guess to simplify my question. I need to store 20 individual inputs from an 'InputDialog' box and store it for later access in a console.
I need to store 20 individual inputs from an InputDialog box and store it for later access in a console.
Use a loop such as for.
That information then gets stored as "Details for car 1 entered:" and then the information displayed.
As I said before, you should use index of array instead of array. And because array is zero-based index, so I use carNumb[i] + 1 to print out the order.
Then calculate fee and store to carNumb array.
Note that, your fee is double type => carNumb should be double type to store correct value.
Full code:
public void enterCar() {
String carInfo;
int carHours;
int i = 0;
double[] carNumb = new double[20];
double fee = Double.parseDouble("7.50");
double sum = 0;
final int MAX = 12;
for (; i < carNumb.length; i++) {
carInfo = JOptionPane.showInputDialog("Please enter the license plate of the car");
carHours = Integer.parseInt(JOptionPane.showInputDialog("Enter the number of hours the car was parked (1-12):"));
System.out.printf("\n");
System.out.printf("Details for car " + (carNumb[i] + 1) + " entered:\n");
System.out.printf("License plate Hours Fee:\n");
System.out.printf("" + carInfo + " " + carHours + " $");
carNumb[i] = getFee(fee, carHours);
System.out.printf("%3.2f", carNumb[i]);
System.out.printf("\n\n");
}
}
private double getFee(double fee, int hours) {
if (hours == 1) {
return fee;
}
if (hours == 2) {
return fee + 4.5;
}
if (hours >= 3) {
return 3 + hours * 4.5;
}
return 0;
}
Did I get your idea?
Hello everyone I am trying to get it so my program is able to take multiple users worth of data, and then print all of that data once the while loop is finished (I have the counter set at 1 so one new set of information can be entered after the last, but if it hits the limit of two people it will stop and print the information). I have been able to get the information to print out correctly using user input data, but I am unable to get more than one person to enter the data, and I was unable to print out more than one set of data even when I was able to take in more than just one user's data. How would I do these two things? Here is my code that i have so far:
public class credLimit {
public static void main(String[]args){
Scanner input = new Scanner(System.in);
int newBalance = 0;
int credCounter = 1;
while(credCounter <= 2){
System.out.print("Enter account number: ");
int accNum = input.nextInt();
System.out.print("Enter your beginning balance: ");
int beginningBalance = input.nextInt();
System.out.print("Enter your total charges this month: ");
int charges = input.nextInt();
System.out.print("Enter your total credit applied this month: ");
int credit = input.nextInt();
System.out.print("Enter your allowed credit limit: ");
int maxcredLimit = input.nextInt();
newBalance = beginningBalance + charges - credit;
credCounter = credCounter + 1;
System.out.printf("%nAccount number: %d%n", accNum);
System.out.printf("Your new balance: %d%n", newBalance);
if(newBalance <= maxcredLimit)
System.out.printf("You have not exceeded your credit limit. %d%n");
else if (newBalance > maxcredLimit)
System.out.printf("Credit limit exceeded. %d%n");
}
}
I was able to take multiple sets of information in before, but now I can only get one of the users data to be taken, calculated (to determine if their credit limit had been exceeded), and printed out. For some reason it keeps stopping at one user's information instead of letting two user's put in their information, why is that?
I'm guessing your code is crashing since you didn't pass in any arguments to those last 2 print statements:
if(newBalance <= maxcredLimit)
System.out.printf("You have not exceeded your credit limit. %d%n");
else if (newBalance > maxcredLimit)
System.out.printf("Credit limit exceeded. %d%n");
Did you mean:
if(newBalance <= maxcredLimit)
System.out.printf("You have not exceeded your credit limit. %d%n", newBalance);
else if (newBalance > maxcredLimit)
System.out.printf("Credit limit exceeded. %d%n", newBalance);
I have this while loop that runs as a user input fee is larger then a transaction amount. For example, if the fee is $4 and you only pay $2, it will say you still owe $2 and prompt you to enter more payments. The problem is that I cannot figure out how to update the variable transaction after a payment if it is still short. After it asks for another payment, say you are still short of the $4 and pay another $1, that will give you a total of $3 and the program should say you are still short by $1. Nonetheless, the program still says you are short by the original amount, i.e. $2.
while (transaction < feeSum)
{
double underPay = feeSum - transaction;
System.out.println("The transaction did not meet the fee by $" + underPay);
System.out.println("Please enter another payment to complete the balance.");
System.out.println("Enter a number of payments.");
int paymentSize2 = keyboard.nextInt();
double[] payments2 = new double[paymentSize2];
System.out.println("Enter " + payments2.length + " payment(s).");
double paymentSum2 = 0;
for(int i = 0; i < payments2.length; i++)
{
payments2[i] = keyboard.nextDouble();
paymentSum2 = paymentSum2 + payments[i];
transaction += paymentSum2; //<<<<<<< Shouldn't this update transaction?
} // The second time around it should say the trans did not meet fee by $1
if (paymentSum2 == underPay)
{
System.out.println("There is now no outstanding balance.");
break;
}
I remade your code a little, this will work, however it doesn't contain all that extra stuff you implemented. I don't really understand why you need those arrays.
This code doesn't handle if you pay more than you should, however that could easily be implemented in the last lines of the while loop.
double underPay = feeSum - transaction;
while (underPay != 0) {
System.out.println("The transaction did not meet the fee by $" + underPay);
System.out.println("Please enter another payment to complete the balance.");
int paymentSizeNext = keyboard.nextInt();
underPay -= paymentSizeNext;
}
System.out.println("There is now no outstanding balance.");