how to complete this program studycase? - java

I got the project assignment in one of the courses and I was confused to finish it. Can you help me to complete this program ?
This is the Study Case.
Make a program to rent hotel room bookings!
Terms:
-Types of Rooms (President Suite, VVIP, Deluxe, Superior)
-Room rates (IDR 1,500,000, - IDR 1,000,000 IDR 800,000 IDR 500,000)
-If staying more than 3 nights, there is a 15% discount
-If the member there is an additional discount of 10%
Input:
-No KTP
-Name
-E-mail
-Gender
-Address
-Phone number
-Type of room
-Length of stay
Output:
-No KTP
-Name
-E-mail
-Gender
-Address
-Phone number
-Type of room
-Room price
-Length of stay
-Discount
-Total pay

I would throw in something here; maybe you can work on top of that. Apparently, the only output values you need to work on are:
Room Price
Discount
Total Pay
That shall simplify the problem a lot. Next up, how to determine Room Price? It seems that flat Room Price is dependent on type of room. Since each type of room has its specific price tag, maybe some data structure in Java can help with that.
Next up, Discount seems to be determined by length of stay. You already have length of stay as input, so figuring out Discount should be straightforward.
Finally, Total Pay seems to be determined by Room Price and Discount. At this point, you shall already have Room Price and length-of-stay discount available. Don’t forget there is also a membership discount, but you have to figure out how to determine membership status.

Related

How to populate/create new classes from Strings/html data? JAVA

Suppose I have a bunch of Strings, I need to now create/write new classes from all of the data. For example, let's say I have the formatted String data here with two items that need to be created:
STAMINA
You have an amazing amount of stamina.
PREREQUISITE: Health 13
BENEFIT: You recover vitality points twice as fast as normal. So, if
you would normally recover 1 hp per level per hour,
with this feat you recover 2 hp per level per hour. A
******* character with this feat recovers 4 hp per
level per hour.
CHITINOUS
You have especially thick armor for a member of your species.
PREREQUISITE: Health 13, damage reduction as a species trait
BENEFIT: The damage reduction you receive as a species trait is
increased by 1. This bonus does not apply
to DR imparted by equipment.
SPECIAL: This feat can be selected multiple times. Each time you
select it, its effects stack.
By this time, this has been added to a hashmap, with the Feat title/name as the key and the rest of the data as a String for the value.
What I need to do now is create new class files for each "Feat", Stamina and Chitnous. So after grabbing the Stamina key and its value (everything after Stamina) from the map, the above data would then result in something like below.
First, a Stamina class that extends the abstract Feat class.
public class Stamina extends Feat {
public Stamina() {
super("STAMINA", "You have an amazing amount of stamina.\n" +
" PREREQUISITE: Health 13\n" +
" BENEFIT: You recover hp twice as fast as normal. So,
if you would normally recover 1 hp per level per hour,
with this feat you recover 2 hp per level per hour.
A ******* character with this feat recovers 4 hp points per
level per hour.");
prereqs.put("CON", 13);//This is a method that populates when seeing "PREREQUISITE" in the String
}
}
Notice there is an additional line that calls a helper method in addition to the call to super(String name, String data).
After this, the algorithm should generate another class file Chitnous and put it in the same directory as the new Stamina class file, however it'd be superfluous for me to write out that example.
Thanks in advance!
TL:DR How do I take Strings and from them write new class files to a target directory in my Android project? To be clear I don't need to initialize objects, I'm trying to populate code from Strings. This would happen in a singleton method/only ever happen once.

Find country code of a mobile number in Java

Is there any way to find the country code of a phone number in Java?
Say if I give 9710334544, I will receive the country code as 91 (if its India).
Any suggestions please.
If the phone number does not include the country code number as prefix, there is no way to find out from which region this phone number originates.
The idea behind the country code is to distinguish the country first, and then parse the number. The reason for this is to forego issues with the same number.
If my U.S. number is 1234567890 then what is there to distinguish that from my U.K number which is 1234567890? The answer is the country prefix. Unfortunately, due to the very nature of this number(in that it distinguishes between numbers that are the same, you can't use the number to figure it out).
Now, if you already have the full 13-14 digit number, you can find the country code by simply dividing (integer division):
long inputPhoneNumber = 123 (XXX) - XXX - XXXX;
long countryCode = inputPhoneNumber / 10000000000l;
// Will give 123
After you have the answer you can match it up with the country, the internet provides several sites that list the codes with their countries:
Country Code

Calculating transaction fees in Java

Lets say you have website that keeps balance for each user. You give each user option to deposit money into their balance from PayPal, Amazon FPS, Authorize.NET eCheck and Credit Card and maybe couple of there once.
Each of the above companies charges fee. And since you are the receiver you are responsible for fees (except for Adaptive PayPal API there you can say who will pay the fees).
So lets say website user (sender) will deposit you $1000.00
And lets picker fee of 2.9% plus $0.30 fix fee = -$29.30
So the receiver (the website owner) ends up with $970.70
If you try to charge $1029.30 you end up with $999.1503
If you try to charge $1031.11 you end up with $1000.90781 which is acceptable (this is when the fee is increased by 0.181% to 3.081% + 0.30)
So this question is, what is the best way to calculate the 0.181% in Java method
I know this is more of math problem than Java problem but what would be the best algorithm to use for guessing the best fee percentage so the final value would get as close as possible to the final value of what the website user is try to deposit.
So the method should take the actual fee 2.9% (0.029 for multiplication), the fix fee 0.30 the amount the user is trying to deposit and figure out the final sum to be charged that would be as close as possible to the deposit amount.
The way I have been doing it is trying to increase the 2.9% until I hit slightly higher after the fees are subtracted.
UPDATE
As per bellow answers I coded up this method. Any further suggestions are more than welcome:
public static float includeFees(float percentageFee, float fixedFee, float amount) {
BigDecimal amountBD = new BigDecimal(amount);
BigDecimal percentageFeeBD = new BigDecimal(1-percentageFee);
BigDecimal fixedFeeBD = new BigDecimal(fixedFee);
return amountBD.add(fixedFeeBD).divide(percentageFeeBD, 10, BigDecimal.ROUND_UP)
.setScale(2, BigDecimal.ROUND_UP).floatValue();
}
Any time you're dealing with money you'll want to use a precision data type rather than floating point math. In general there are rules about how you round on matters when dealing with things like sales tax.
BigDecimal has parameters you can set to control the rounding behavior that will probably get you to where you need to go. In any case like this the math will never be exact on fractions of a cent but you should be able to guarantee that you'd never charge more than an extra fraction of a penny.
amt_you_receive = amt_customer_pays - .029 * amt_customer_pays - .30
amt_you_receive + .30 = amt_customer_pays * (1 - .029)
(amt_you_receive + .30) / .971 = amt_customer_pays
So take the amount you want to get, add 30 cents, and divide by .971 (aka multiply by approximately 1.029866) to get the amount you should charge.

Need help with Java homework

I need some help with my homework assignement. My assignment is to create a program that creates a Till object, takes a payment, issues exact change, tells me which coins I need to use and then tells me how much is in the till after. Below is the code I have written. The USmoney class is done and is working. The teacher offered a cheat sheet. However it's the main class (CoinCalc), getting the till to take the payment and subtract the payment from the amount paid to give me the change that I'm having issues with. Any help would be most appreciated.
public class USmoney {
int dollars = 0;
int cents = 0;
public USmoney(int newcents) {
dollars = newcents /100;
cents = newcents %100;
}
public USmoney(int dollars, int cents) {
this.dollars = dollars;
this.cents = cents;
}
public int getDollars() {
return dollars;
}
public int getCents(){
return cents;
}
}
public class CoinCalc {
public static void main(String[] args) {
USmoney Till1 = new USmoney(100,0);
USmoney billTotal = new USmoney(49);
USmoney amountPaid = new USmoney(100);
double penny = 1;
double nickel = 5;
double dime = 10;
double quarter = 25;
double[] Coin = new double []{penny,nickel,dime,quarter};
}
private void changeFor(USmoney billTotal, USmoney amountPaid) {
}
}
This is a varient of the knapsack problem, you have a couple of steps to implement
Calculate total change
Satisfy change using smallest number of coins
I'd start by implementing a method with the first signature in your USMoney class, and then read up on the knapsack problem in order to implement the second method.
public USMoney subtract(final USMoney value);
public double[] getCoins(final USMoney value);
There are two issues here, which you can consider separately.
Are you able to describe algorithmically how to determine the answer to your question?
Given this description, can you turn it into Java code?
I'll start by addressing the first item: It is essential that you understand exactly what the input is and what the required output is and that you are able to give a precise pseudo code description of how to solve the problem. If you don't know what pseudocode is, then look it up on Wikipedia. Then you can start thinking about how to code it in Java.
From an algorithmic perspective, your problem is very simple.
Say the customer pays amount X and for an item that costs amount C.
First you must check that X >= C. otherwise the customer won't have paid enough, and you can stop right there.
Assuming that X >= C, and that you are able to give exact change, the amount of money in the till will have increased by C after the transaction completes, as this exactly what the customer ends up paying.
Now, the amount of change you have to give should equal X-C. Call this Y.
Test how many times the biggest coin you have available divides Y:
Say the biggest coin has value V, then you should give back the customer Y/V coins of this value.
Afterwards, you need to pay back the customer the remaining money Y'=Y-(Y/V)*V. Make sure you know how division works in Java (see link at the end of this post).
Repeat the procedure to pay Y' back using the second biggest coin and so on.
2.
I won't write out the whole thing in Java, but there are some things you should consider.
Does the Till contain "money" without it being specified exactly what bills/coins it contains, or should you be representing the money as a number of bills and coins?
You will be doing integer division, so your coin values should not be doubles but ints.
You need to access the coin values (how much a dime is worth etc.) from inside the function that calculates change, so the values of the different coins should probably be declared as static member variables of the class CoinCalc, not inside a function.
You need to make sure you know how basic if-else statements and while loops work and how to assign to variables. Then you should be able to code the solution.
You also need to decide what exactly the solution is. It could be a list of coin names with a name repeated for each time it is needed, e.g. [dime,penny,penny], or maybe an array of four numbers with that say how many quartes, dimes, nickels and pennies are needed. If you want a list, you should learn how list datastructures work in Java, by reading the entry LinkedList in the Java documentation.
Good luck!
NB: Because I'm a new user, I can't post as many links as I would like. You can find a good description of division in Java by googling java division and selecting the link to mindprod.com.
It looks like you want help with your changeFor algorithm, so here's an outline:
First subtract billTotal from amountPaid. That will get you how much change to make.
Then make some variables to hold how much change you're giving back. For each of quarter, dime, nickel, penny, if changeRemaining is > the value of the coin, add a coin and subtract the value. Do this for each coin in order until that coin's value fails the test, then move on to the next coin.
In order to call the changeFor() method you need a reference to a CoinCalc class. You can do this different ways, one way is to declare a variable of the CoinCalc class in the main() method like so:
CoinCalc cc = new CoinCalc();
cc.changeFor(billTotal, amountPaid);
But there are still problems, the method changeFor() currently does nothing and the way you have declared the till object and coin array they are not accessible in the changeFor() method.
So work on that problem for a bit then get back to us...
EDIT
Here is how I would structure it, billTotal is a float amountPaid is a USMoney object that internaly keeps track of each denomination of money ($1 bill, quarter, dime, nickel and penny). When someone pays they give you differing amounts of those kinds of money. USMoney needs and method that will return the value of the kinds of money it has (sum of dollars, quarters, etc).
till is another instance of USMoney that has an initial value of the different denominations of money.
USMoney has a method called changeFor(float bill, USMoney paid) that returns another instance of USMoney. You would then call it like so:
USMoney change = till.changeFor(bill, amountPaid);
The changeFor() method then has to determine how to make change based on what is in the till and the difference between bill and the value of amountPaid. NOTE if you don't have enough quarters your calculations should be smart enough to use dimes and nickels if it has enough. If you want to really get clever throw an exception if you can't make change.

Estimating a probability given other probabilities from a prior

I have a bunch of data coming in (calls to an automated callcenter) about whether or not a person buys a particular product, 1 for buy, 0 for not buy.
I want to use this data to create an estimated probability that a person will buy a particular product, but the problem is that I may need to do it with relatively little historical data about how many people bought/didn't buy that product.
A friend recommended that with Bayesian probability you can "help" your probability estimate by coming up with a "prior probability distribution", essentially this is information about what you expect to see, prior to taking into account the actual data.
So what I'd like to do is create a method that has something like this signature (Java):
double estimateProbability(double[] priorProbabilities, int buyCount, int noBuyCount);
priorProbabilities is an array of probabilities I've seen for previous products, which this method would use to create a prior distribution for this probability. buyCount and noBuyCount are the actual data specific to this product, from which I want to estimate the probability of the user buying, given the data and the prior. This is returned from the method as a double.
I don't need a mathematically perfect solution, just something that will do better than a uniform or flat prior (ie. probability = buyCount / (buyCount+noBuyCount)). Since I'm far more familiar with source code than mathematical notation, I'd appreciate it if people could use code in their explanation.
Here's the Bayesian computation and one example/test:
def estimateProbability(priorProbs, buyCount, noBuyCount):
# first, estimate the prob that the actual buy/nobuy counts would be observed
# given each of the priors (times a constant that's the same in each case and
# not worth the effort of computing;-)`
condProbs = [p**buyCount * (1.0-p)**noBuyCount for p in priorProbs]
# the normalization factor for the above-mentioned neglected constant
# can most easily be computed just once
normalize = 1.0 / sum(condProbs)
# so here's the probability for each of the prior (starting from a uniform
# metaprior)
priorMeta = [normalize * cp for cp in condProbs]
# so the result is the sum of prior probs weighed by prior metaprobs
return sum(pm * pp for pm, pp in zip(priorMeta, priorProbs))
def example(numProspects=4):
# the a priori prob of buying was either 0.3 or 0.7, how does it change
# depending on how 4 prospects bought or didn't?
for bought in range(0, numProspects+1):
result = estimateProbability([0.3, 0.7], bought, numProspects-bought)
print 'b=%d, p=%.2f' % (bought, result)
example()
output is:
b=0, p=0.31
b=1, p=0.36
b=2, p=0.50
b=3, p=0.64
b=4, p=0.69
which agrees with my by-hand computation for this simple case. Note that the probability of buying, by definition, will always be between the lowest and the highest among the set of priori probabilities; if that's not what you want you might want to introduce a little fudge by introducing two "pseudo-products", one that nobody will ever buy (p=0.0), one that anybody will always buy (p=1.0) -- this gives more weight to actual observations, scarce as they may be, and less to statistics about past products. If we do that here, we get:
b=0, p=0.06
b=1, p=0.36
b=2, p=0.50
b=3, p=0.64
b=4, p=0.94
Intermediate levels of fudging (to account for the unlikely but not impossible chance that this new product may be worse than any one ever previously sold, or better than any of them) can easily be envisioned (give lower weight to the artificial 0.0 and 1.0 probabilities, by adding a vector priorWeights to estimateProbability's arguments).
This kind of thing is a substantial part of what I do all day, now that I work developing applications in Business Intelligence, but I just can't get enough of it...!-)
A really simple way of doing this without any difficult math is to increase buyCount and noBuyCount artificially by adding virtual customers that either bought or didn't buy the product. You can tune how much you believe in each particular prior probability in terms of how many virtual customers you think it is worth.
In pseudocode:
def estimateProbability(priorProbs, buyCount, noBuyCount, faithInPrior=None):
if faithInPrior is None: faithInPrior = [10 for x in buyCount]
adjustedBuyCount = [b + p*f for b,p,f in
zip(buyCount, priorProbs, faithInPrior]
adjustedNoBuyCount = [n + (1-p)*f for n,p,f in
zip(noBuyCount, priorProbs, faithInPrior]
return [b/(b+n) for b,n in zip(adjustedBuyCount, adjustedNoBuyCount]
Sounds like what you're trying to do is Association Rule Learning. I don't have time right now to provide you with any code, but I will point you in the direction of WEKA which is a fantastic open source data mining toolkit for Java. You should find plenty of interesting things there that will help you solve your problem.
As I see it, the best you could do is use the uniform distribution, unless you have some clue regarding the distribution. Or are you talking about making a relationship between this products and products previously bought by the same person in the Amazon Fashion "people who buy this product also buy..." ??

Categories

Resources