Calculate total bill and Subtotals - java

Write a program that reads the total number of pieces of oranges, eggs, apples, watermelons, and bagels they purchased. Calculate the total bill and subtotals for each item using the following prices:
a.Oranges: 10 for 2.99/0.50 each
b.Eggs: 12 for 1.69/0.25 each
c.Apples: 3 for 1.00/0.75 each
d.Watermelons: 4.39 each
e.Bagels: 6 for 3.50/0.95 each
I'm a little bit confused for on what method should I use to program/solve this problem? I'm thinking to use a If statement but I think it's not a good idea. How should i start my coding? This is my first time encountering a price system with (I think discount?) fix amount of price on each item. It's bothering me to think that how can i do a "2.99 for 10 apples" while one apple is 0.50?" should I use discount? My mind is bleeding right now -_-

Here is an algorithm for solving the problem. Go step by step and implement the logic. I am sure you will get the final result.
Take the count for one fruit and display it.
From the count, calculate the sub-total price by taking the rate as per piece. Display the sub-total.
Store the sub-total you got in 2nd step in a separate variable and display it.
Follow the steps 1 to 3 for other fruits now, storing the sub-total of each fruit in a separate variable.
Calculate the final total by adding the values of all sub-total variables.
For applying the discounts, you can use a simple if...else logic along with some arithmetic operators.
6.1 Divide the count by 10 (for oranges) and store it in a variable called tmp.
6.2 If tmp is greater than 0,
subTotal = tmp * price_of_10
count = count - (tmp * 10)
subTotal = subTotal + (count * price_of_1)
6.3 If tmp is equal to zero
subTotal = count * price_of_1

I can help you get started. I don't want to give you all the code because I still want you to learn from it.
//Read number of Oranges here
//Some code
if(number = 10) price = 2.99
else price = number*0.50
total += price
Repeat for other products, don't forget to change the price value
EDIT: if you want to buy more than 10 and still get the discount, you will need to do something like this
int ten = 0;
Double rest =0;
if(number/10 >= 1){
ten = number/10;
rest = number%10;
price = ten*2.99 + rest*0.50;
}else{
price = number*0.50
}
total += price

Related

Getting negative values while incrementing numbers in a while loop

I am trying to create a program that will calculate how many days I will need to save X amount of money if I increment the daily contribution by the previous and initial values every day.
Eg: my starting contribution on day 1 is 2, then on day 2 it will be 4, day 3 it will be 6 etc, so the total money in the pot for 3 days will be 12.
My program at the moment looks like this:
int startingValue = 2;
int dailyAmount = startingValue;
int pot = 0;
int desiredMoney = 43554;
int daysSaved =0;
while (pot != desiredMoney){
pot += dailyAmount;
dailyAmount += startingValue;
daysSaved++;
}
System.out.println("Daily amount needed : " + dailyAmount + " Days saved : " + daysSaved + " Money in the pot : " + pot);
Current output of this program is this :
Daily amount needed : 294923972 Days saved : 147461985 Money in the pot : 43554
which doesn't look quite right, but I am not sure why. When I run it in debug mode, it makes sense for the first couple of runs, but when I put the sout statement inside the while loop after a while I see negative numbers such as these:
Daily amount needed : 1054054 Days saved : 527026 Money in the pot : -1415942538
I would expect to see daysSaved as around 1000 days, but my program is clearly broken. Will appreciate any help!
First: why do you get negative numbers when adding? Integer Overflow. Java's ints are 32 bit signed integers. The max safe value for a signed integer is 2147483647. Add just 1 to that it will roll over into -2147483648.
Read more about integer overflows on Wikipedia.
For the second part of your question. pot != desiredMoney is very unlikely to happen, since you keep adding an ever increasing number to your pot. The semantic you want is probably pot < desiredMoney; keep doing this loop while the pot is less than the desired amount of money.

mortgage calc returning negatives

I'm trying to deal with money (probably the wrong way as far as best practices but I thought it would work.. its simple, multiply everything by 100 and then use ints)
import java.util.Scanner;
public class PFiveFifteen {
public static void main(String[] args)
{
Scanner in =new Scanner(System.in);
int i = 0;
double principalIn;
int duration=0;
double interestRate=0;
int thisYear = 0;
int iInterestRate = 0;
int iPrincipalIn = 0;
System.out.println("Please input initial amount: ");
principalIn = in.nextDouble();
iPrincipalIn= (int) principalIn *100;
//System.out.println(principalIn*100);
System.out.println("Please input interest rate as a decimal: ");
interestRate = in.nextDouble()*100;
iInterestRate = (int) interestRate;
//System.out.println(interestRate*100);
System.out.println("Please input duration of investment in years: ");
duration = in.nextInt();
//System.out.println(duration);
while(duration > i ) {
if ( i == 0) {
//System.out.println("Preloop value" + (iInterestRate));
thisYear = (iPrincipalIn * iInterestRate)+ iPrincipalIn;
//System.out.println("Postloop value" + (iPrincipalIn));
i++;
System.out.println("The initial value is " + thisYear);
System.out.println("Year # one one: " +i);
}
else
thisYear = (thisYear*iInterestRate) + thisYear;
i++;
System.out.println(thisYear/10000);
System.out.println("year # " +i);
}
But I'm somehow getting negative numbers back in console
Please input initial amount:
10000
Please input interest rate as a decimal:
100.00
Please input duration of investment in years:
10
The initial value is 1411065408
Year # one one: 1
141106
year # 2
-119738
year # 3
-72104
year # 4
4904
year # 5
84261
year # 6
21917
year # 7
154073
year # 8
-145664
year # 9
63722
year # 10
What in the world is going on here? I could get if there where whacky decimals or soemthing ( even though I cast it all to ints) but what the dickens is taking all positive inputs to below zero??
Your idea of representing money amounts as integers is an OK one, but you have to be very careful of the scaling, especially when you multiply (or divide). Say you start with a principal of $10, which you represent as 1000. Then you enter an interest rate of 0.06 (I assume that the user is entering an actual rate and not a percentage, so 0.06 means 6%). You then represent that as 6.
So if your principal is P, the int you're using to represent it is P*100. And if your interest rate is I, the int you're using to represent it is I*100.
So now you want to compute P*I. Since you're representing everything as 100 times the actual value, you presumably want to get an int whose value is P*I*100. But when you multiply the two ints you have, P*100 and I*100, the result is P*I*10000 -- a factor of 100 too high. That's because you multiplied the scale factors together along with the values. I can see that you did output thisYear / 10000, but you didn't change thisYear. So as you keep going through the loop, you will get values that are a factor of 10000 too high, and 1000000 too high, and so on, and eventually you will overflow. (I wish things really did work that way, but unfortunately I can't talk my bank into using your algorithm.)
To adjust, you'll need to divide this result by 100. (I'd add 50 to it first, so that when you divide by 100 the result will be rounded.)
looks like using ints was just ill conceived.
I did get it to play right with smaller numbers (the biggest issue was having to again bump up the principal by 100 to keep the correct place holder for when the interest which was (p*100)*(i*100) otherwise it was something *100 being added to the interest which was *10000. Sadly any realistic amount of money (like say 250000 for a house) overflows it before the first loop. Though 200000 makes it all the way to loop 30.
Plus interest rates aren't always hundredths, sometimes they are something like .03875
My code lacks the ability to determine the length and even if it had it bumping that up to an int, and keeping everything else like it (multiplying everything by 100000) would definitely not work.
Props to community for not calling me an idiot though! on Youtube et al, I would have gotten answers that would have put me into a corner crying!

Rounding Issue with my code. Need it for homework assignment. My code is working correctly. I am using Java

This is a homework question that has been asked a lot, but I am having trouble with the final formatting of the output. This is the question:
Population
Write a program that will predict the size of a population of organisms. The program should ask the user for the starting number of organisms, their average daily population increase (as a percentage, expressed as a fraction in decimal form: for example 0.052 would mean a 5.2% increase each day), and the number of days they will multiply. A loop should display the size of the population for each day.
Prompts, Output Labels and Messages .The three input data should be prompted for with the following prompts: "Enter the starting number organisms: ", "Enter the daily increase : ", and "Enter the number of days the organisms will multiply: " respectively. After the input has been read in successfully, a table is produced, for example:
Day Organisms
-----------------------------
1 200.0
2 300.0
3 450.0
4 675.0
Under the heading is a line of 29 dashes followed by one line for each day, showing the day number and the population at the beginning of that day.
Input Validation.Do not accept a number less than 2 for the starting size of the population. If the user fails to satisfy this print a line with this message "Invalid. Must be at least 2. Re-enter: " and try to read the value . Similarly, do not accept a negative number for average daily population increase , using the message "Invalid. Enter a non-negative number: " and retrying. Finally, do not accept a number less than 1 for the number of days they will multiply and use the message "Invalid. Enter 1 or more: ".
That is my code below:
import java.util.Scanner;
public class Population
{
public static void main(String[] args){
double organism;
int days;
double increase;
Scanner input = new Scanner(System.in);
System.out.print("Enter the starting number organisms: ");
organism = input.nextDouble();
while(organism < 2){
System.out.print("Invalid. Must be at least 2. Re-enter: ");
organism = input.nextDouble();
}
System.out.print("Enter the daily increase: ");
increase = input.nextDouble();
while(increase < 0){
System.out.print("Invalid. Enter a non-negative number: ");
increase = input.nextDouble();
}
System.out.print("Enter the number of days the organisms will multiply: ");
days = input.nextInt();
while(days < 1){
System.out.print("Invalid. Enter 1 or more: ");
days = input.nextInt();
}
System.out.println("Day Organisms");
System.out.println("-----------------------------");
System.out.println("1"+ " " +organism);
for( int i = 2; i <= days; i++){
organism = organism*(increase + 1);
System.out.print(i+" "+organism);
System.out.println();
}
}
}
The problem I am having is when I submit it online. The output my code produces after 20 days with 0.4 or 40% rate of increase and initial amount of 20 organisms is this:
Days Organisms
20&rarr&rarr11952.607917897816↵
What it wants is this:
20&rarr&rarr11952.607917897836↵
This may be unclear. It is how the errors are being shown using Myprogramminlab(a web application to submit homework).
&rarr means right arrow which is a tab and the number 11952 is the number of organisms, but it is being rounded differently.
Also, at 3 days:
Expected is 39.2 My Ouptut is 39.19999999999996
It is basically a small rounding issue. Please help
This is a really small fraction, and in the cases of populations I think it doesn't really matter. If It was up to me I would accept your solution without hesitation.
You can however reach a little more precision even if you use simple doubles, if you write your code like this:
double multiplication = 1;
for( int i = 1; i <= days; i++){
System.out.print(i+" "+organism*multiplication);
multiplication = multiplication * (increase + 1);
System.out.println();
}
Floating point types have the property that they have a bigger precision for number with a smaller absolute value. The value of multiplication will be significantly smaller then the value of organism, so the aggregated rounding (representation) error will also be smaller.
Thanks everyone. I tried what you suggested and it did make it more precise. However, the assignment was still being marked as incorrect. I tried this instead:
System.out.println("1"+ " " +organism);
for( int i = 2; i <= days; i++){
organism += organism*increase;
System.out.println(i+" "+organism);
}
For some reason that was okay. Thanks again though, I really appreciate the help!

Sort a 2d array by two separate columns

Right now I've got a method that can get data from a 2D array, throw it into a Arraylist and then lets me retrieve only the particular parts from that Arraylist that I want.
The code below loops through the races Arraylist and places the racers, the total times and how many events they take part in into an array, as of yet unordered in any way.
if (!Found && selected.equals(race.GetCat()))
{
ranking[j][0] = race.GetComp();
ranking[j][1] = race.GetCat();
ranking[j][2] = (GetSecs(race.GetRace1()))
+ (GetSecs(race.GetRace2()))
+ (GetSecs(race.GetRace3())) + "";
n++;
};
Found= false;
for (int i = 0; i < locations.size(); i++)
{
for (Race race: races)
{
if (race.GetComp().equals(array[i][0]) && option.equals(array[i][1]))
{
seconds += (GetSes(race.GetRace1()))
+ (GetSes(race.GetRace2()))
+ (GetSes(race.GetRace3()));
total= GetMin(seconds);
counter++;
}
ranking[i][2] = total2 + "";
ranking[i][3] = counter + "";
}
}
So ranking prints out like
RACER TOTAL TIME EVENTS TAKING PART IN
name 230.44 2
name 142.51 4
name 523.01 7
name 444.55 2
name 432.18 4
And ordering the rankings (String) array so that it is sorted via perhaps the number of events or the total time of the races would not be too difficult.
However, more than one racer will take part in the same number of events, so I was wondering what process or code I would have to go through in order to order the array based on the number of events, and then check to see which rankings share the number of events, and then switch them around based on which total time is lowest
So rankings sorted like
george 500 5
john 400 5
george 500 4
david 300 3
carl 200 3
is sorted like
john 400 5
george 500 5
george 500 4
carl 200 3
david 300 3
If something like that is possible. I can put them into an array, and even sort them by one particular column, but sorting them by one, and then by another if the first column has numbers are are the same is totally beyond me, if any of this post makes sense.
Check out:
Column Comparator. It allows you to sort on any column in an ArrayList.
Group Comparator. It allows you to sort on multiple columns at the same time.

Algorithm to compare multiple values

In my class, i have to calculate prices of 18 different building which have different prices and income. They also have changes in price when the money of quantity of the building increases.
For example: The building starts at 40 dollars when the quantity is 0. The price increments by 4 for each quantity. So if you own 1, the price to buy the next same building will be 44 in state of 40. So this is the method that will calculate the price just fine.
public float getBuildingPrice(float quantity)
{
float buildingNum = quantity;
float startingPrice = 40;
float costIncrease = 4;
float finalPrice;
finalPrice = startingPrice + (costIncrease*buildingNum);
return finalPrice;
}
The method above returns the price and i divided the calculated price with the income that comes to the building like this. 10 is the income
float storageWorth = buildingPrice/10;
The thing i am unable to do is to find out the amount of different building the user can buy in the most efficient way ( meaning highest income but lowest spending ) So it should be the lowest Price / income that should be fulfilling the condition but also keeping in mind that it must be in the budget that the user keys in. There is always a change in the price and i do not know how to compare multiple values ( 18 values ) with the extra condition to keep in the budget.
For example
Farm
Income - 1
5 buildings
Increment of 4
Price 40 + (5 * 4) = 60
Price over income = 60
Pen
Income - 5
4 Buildings
Increment of 20
Price 200 + (4 * 20) = 280
Price over income 280/5 = 56
So meaning to say the next building the user should buy is a pen because it has lower price/income. There is also chances that the price over income of both building is the same like if the building reaches 5 for pen building, both price over income of pen and farm will be 60.
This is a formulation of your problem that ends up a mixed integer and non linear programming problem:
For all building type i let's define:
Pi : price of building type i
Ci : Price increment of building type i
Mi : income for building type i
B : Budget
Ni : Number of buildings of type i purchased.
Purchasing Ni building of type i equals:
Sum for j=1 to Ni Pi + (j - 1) × Ci = Ni (Pi + ( Ni - 1) / 2 × Ci)
Mixed integer non linear programming formulation:
Maximise Sum for i Ni × Mi
Subject to : sum for i Ni (Pi + (Ni - 1) / 2 ×Ci) <= B
Note that Pi, Ci, Mi and B are constants. Decision variables are Ni
An other solution is to purchase a building at a time selecting the one with the maximum income per invested money as per the following ratio:
Mi / (Ni (Pi + ( Ni - 1) / 2 × Ci))
At each step you calculate the building with the maximum ratio, purchase a building, deduct the price of the budget and repeat until the budget is exhausted. I do not have a proof that you will get an optimum my following this algorithm.
Third solution pseudocode (brute force):
(income, index_list) function maximize_income(i, b)
if i > last_building_type
return 0, []
endif
max_income = 0
max_income_index = 0
while b >= P(i) - (j-1) * C(i)
b = b - P(i) - (j-1) * C(i)
(income, index_list) = maximize_income(i+1, b)
income = income + j * M(i)
if income > maximum_income
maximum_income = income
maximum_income_index = j
endif
endwhile
add maximum_income_index to index_list
return maximum_income, index_list
end function
index_list is an array containing the number of each type of building
Your problem is a linear programming problem. Such problems don't have easy answers.
To solve such problems, people have invented many smart algorithms like the Simplex Algorithm.
These alogrigthms work on a represenation of the problem that basically is a set of mathematical linear equations. You have to think hard about your problem and formulate these equations.
A C library to solve a LP problem forumlated this way is the GLPK (GNU Linear Programming Kit). There are frontends for Python and for Java.
Your question is not a programming problem. It is a mathematical problem that can be solved in any language. Give enough time, it can even be solved on paper.

Categories