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.");
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.
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 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.
I am having issues with a problem that I coded for a Java course I am taking, and I cannot figure out why it is behaving a certain way. Here is the problem from the book, both part A and part B:
A) Create a class named Purchase. Each Purchase contains an invoice number, amount of sale, and amount of sales tax. Include set methods for the invoice number and sale amount. Within the set() method for the sale amount, calculate the sales tax as 5% of the sale amount. Also include a display method that displays a purchase's details. Save the file as Purchase.java
B) Create an application that declares a Purchase object and prompts the user for purchase details. When you prompt for an invoice number, do not let the user proceed until a number between 1000 and 8000 has been entered. When you prompt for a sale amount, do not proceed until the user has entered a non-negative number, sale amount, and sales tax. Save the file as CreatePurchase.java.
Here is the code for the first part of the problem:
public class Purchase
{
int invoiceNumber = 1234;
double salePrice = 10.00;
double SalesTax;
public void setInvoiceNumber(int invoice)
{
invoiceNumber = invoice;
}
public void setSalePrice(double saleAmount)
{
salePrice = saleAmount;
SalesTax = (saleAmount * .05);
}
public void displaySalePrice()
{
System.out.println("Your invoice number is:" + invoiceNumber + ".");
System.out.println("Your sale amount is: " + salePrice + ".");
System.out.println("Your sales tax is: " + SalesTax + ".");
}
}
Here is the code for the second part of the problem:
import java.util.Scanner;
public class CreatePurchase
{
public static void main(String[] args)
{
int invoice;
double saleAmount;
invoice = 0;
saleAmount = 0.0;
Purchase completedPurchase = new Purchase();
Scanner input = new Scanner(System.in);
System.out.println("Please enter the invoice number: ");
invoice = input.nextInt();
System.out.println("Please enter the sale amount: ");
saleAmount = input.nextDouble();
do
{
System.out.println("You entered an invalid number.");
System.out.println("Please enter a number between 1000 and 8000.");
invoice = input.nextInt();
}
while (invoice < 1000 || invoice > 8000);
do
{
System.out.println("You entered an invalid number.");
System.out.println("Please enter a number greater than 0.");
saleAmount = input.nextDouble();
}
while (saleAmount < 0);
completedPurchase.setInvoiceNumber(invoice);
completedPurchase.setSalePrice(saleAmount);
completedPurchase.displaySalePrice();
}
}
When I compile CreatePurchase.java and run it, it works, but has to cycle through the loops first before it works. For instance, I will type in 7000 for the invoice value and 100 for the sale amount. Those two values should automatically call the completePurchase.displaySalePrice(); method because the invoice number is greater than 1000 and less than 8000, and the sale amount is greater than 0. That being the case, it still cycles through the do while loops once before calling that method.
I cannot for the life of me figure this out. It's probably something pretty simple I am missing. Any help would be greatly appreciated.
After the great guidance of everyone below, I changed the code for the loops to the following:
while (invoice < 1000 || invoice > 8000)
{
System.out.println("You entered an invalid number.");
System.out.println("Please enter a number between 1000 and 8000.");
invoice = input.nextInt();
}
while (saleAmount < 0)
{
System.out.println("You entered an invalid number.");
System.out.println("Please enter a number greater than 0.");
saleAmount = input.nextDouble();
}
It still isn't working correctly. Changing the loops to while loops certainly worked, but now when I enter a number for the invoice number that's in the correct range and an incorrect number for the saleAmount, the program finished and does not execute the while loop for saleAmount? I seem to be missing a concept here.
Also, can anyone recommend a better IDE than JGrasp. That is what we were told to use, but it's cumbersome. I have VisualStudio and Eclipse, but I feel that doing java homework in those two IDE's might be overkill. I will be taking more java courses and c++ courses, so maybe it's worth learning the basics in VS or Eclipse. Any suggestions would be appreciated.
That is because the do block always gets executed at least once. You should use a while loop instead:
while (invoice < 1000 || invoice > 8000)
{
System.out.println("You entered an invalid number.");
System.out.println("Please enter a number between 1000 and 8000.");
invoice = input.nextInt();
}
This way, you only ask for another number, if the invoice number is not between the range you defined.
That's how do...while loops work: the body is executed once, and then the condition is checked. Use a normal while loop instead.
It's because you're using do{ } while(...) instead of while(...) { }
The do while is guaranteed to run at least once, and then continue looping.
The while will never run if the initial condition is false.
In do-while loops, the body is executed before the condition is tested. You probably want to be using while loops, where the body is executed after the condition is tested.
I highly suggest you read about the difference from Sun's while and do-while tutorial.
Change your loops to whiles
while (invoice < 1000 || invoice > 8000)
{
...
}
When I complie CreatPurchase.java and run it, it works, but has to cycle through the loops first before it works.
That's because you're using a do...while loop. A do...while loop executes at least once, and checks the condition after executing the body of the loop.
What you want in this case is a simple while loop, so that the condition is checked before executing the body of the loop. ie:
while (invoice < 1000 || invoice > 8000)
{
...
}
There are several loop functions in Java, one is the do-while-loop which always executes once and then if the while-part is true it loops again.
Another, and better in this case, is the while-loop that works the same but checks the while-part before the first loop.
Check out the tutorial
You need a while (condition) {…} loop. This way the code in the loop will be executed only if the condition is true. In your code you have a do … while(condition) loop and the inside of the loop will always be executed at least once.
import java.util.Scanner;
public class CreatePurchase {
public static void main(String[] args) {
int invoice;
double amount;
Purchase sale1 = new Purchase();
System.out.println("Enter invoice number between 1000 and 8000 >>");
Scanner input = new Scanner(System.in);
invoice = input.nextInt();
while (invoice < 1000 || invoice > 8000) {
System.out.println("You entered a wrong invoice number");
System.out.println("Enter invoice number between 1000 and 8000 >>");
invoice = input.nextInt();
}
System.out.println("Enter sales amount >>");
amount = input.nextDouble();
while (amount < 0) {
System.out.println("Enter number greater than 0 ");
System.out.println("Enter sales amount >>");
amount = input.nextDouble();
}
sale1.setInvoiceNumber(invoice);
sale1.setAmount(amount);
sale1.display();
}
}