Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
The code doesn't work right the program runs both if statements and the total never comes out right. I can't figure out whats wrong. what changes do i need to make for this to work? the directions are below.
The cost to become a member of a fitness center is as follows: (a) the Senior
citizens discount is 30%; (b) if the membership is bought and paid for 12 or
more months in advance, the discount is 15%; or (c) if more than 5 personal
training sessions are purchased, the discount on each session is 20%.
Write a menu driven program that determines the cost of a new membership.
Your program must contain a method that displays the general information about
the fitness center and its charges, a method to get all the necessary information
to determine the membership cost, and a method to determine the membership
cost. Use appropriate parameters to pass information in and out of a method.
what methods should i use?
double grossdiscount1,grossdiscount2,grossdiscount3;
double grossprice1,grossprice2,grossprice3;
//end result of box calculation
double answerbox1,answerbox2,answerbox3;
double answerbox1b,answerbox2b,answerbox3b;
//Jtext inputs
double box1,box2,box3;
double discount1 = 0.30 ;
double discount2 = 0.20 ;
double discount3 = 0.15 ;
// prices PT=personal training MT=montly price
double pricePT =50.00;
double priceMT =100.00;
box1 = Double.parseDouble(jTextField1.getText());
box2 = Double.parseDouble(jTextField2.getText());
box3 = Double.parseDouble(jTextField3.getText());
// i brought these out of the if statement because the program won't run without
// them being stated
answerbox1b=box1*100;
grossdiscount1=(box1*priceMT)*discount3;// the amount saved
grossprice1=(box1*priceMT);
answerbox1=(grossprice1-grossdiscount1);
answerbox2b=(box2*pricePT);
grossdiscount2=(box2*pricePT)*discount2;// the amount saved
grossprice2=(box2*pricePT);
answerbox2=(grossprice2-grossdiscount2);
double total = answerbox1+answerbox2+answerbox1b+answerbox2b;
grossdiscount3=(total*discount3);// the amount saved
grossprice3=total;
answerbox3=(grossprice3-grossdiscount3);
if(box1<11 )
{
answerbox1b=box1*100;
}
else if(box1>12)
{
grossdiscount1=(box1*priceMT)*discount3;// the amount saved
grossprice1=(box1*priceMT);
answerbox1=(grossprice1-grossdiscount1);
}
if(box2<5 )
{
answerbox2b=(box2*pricePT);
}
else if(box2>=5)
{
grossdiscount2=(box2*pricePT)*discount2;// the amount saved
grossprice2=(box2*pricePT);
answerbox2=(grossprice2-grossdiscount2);
}
if(box3==1 )
{
grossdiscount3=(total*discount3);// the amount saved
grossprice3=total;
answerbox3=(grossprice3-grossdiscount3);
}
else if(box3==0);
{
}
jTextField4.setText(String.valueOf(total));
The else if statements are not written correctly. Remove the ; for a correct flow.
And I also recommend you to check any of the threads related to comparing doubles in Java
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I need some guidance as how can I optimize the below code. As one can see , i am creating a new object everytime to set each value. How can I do it in a better way
Balance[] balance = new Balance[3];
CurAmt curAmt = new CurAmt();
Balance bal = new Balance();
bal.setBalType("currentBalance");
curAmt.setCurCode(entry.getValue().get(0).getAs("CURRENT_BALANCE_CURRENCY_CODE"));
curAmt.setContent(entry.getValue().get(0).getAs("CURRENT_BALANCE"));
bal.setCurAmt(curAmt);
balance[0] = bal;
CurAmt curAmt1 = new CurAmt();
Balance bal1 = new Balance();
bal1.setBalType("availableBalance");
curAmt1.setCurCode(entry.getValue().get(0).getAs("AVAILABLE_BALANCE_CURRENCY_CODE"));
curAmt1.setContent(entry.getValue().get(0).getAs("AVAILABLE_BALANCE"));
bal1.setCurAmt(curAmt1);
balance[1] = bal1;
CurAmt curAmt2 = new CurAmt();
Balance bal2 = new Balance();
bal2.setBalType("interestEarnedYtd");
curAmt2.setCurCode(entry.getValue().get(0).getAs("YTD_CURRENCY_CODE"));
curAmt2.setContent(entry.getValue().get(0).getAs("TD_AMOUNT"));
bal2.setCurAmt(curAmt2);
balance[2] = bal2;
Obj.setBalance(balance);
If you are talking about code performance, I can only see one optimization. You evaluate this 6 times, and the JIT compiler probably can't optimize it:
entry.getValue().get(0)
Do it once and assign the value to a temporary variable. (It is unclear if this will make a significant difference. And you were just doing this for performance reasons, you would be advised to profile your application first. There is no point in optimizing application code that is not a performance hotspot.)
If you are talking about programmer efficiency (i.e. code readability) I can see a block of code that is repeated 3 times with different parameters. You can turn it into a method; e.g.
private Balance createBalance(Value v, String type, String currency, String balance) {
CurAmt curAmt = new CurAmt();
Balance bal = new Balance();
bal.setBalType(type);
curAmt.setCurCode(value.getAs(currency));
curAmt.setContent(value.getAs(ballance));
bal.setCurAmt(curAmt);
return bal;
}
then call it with the appropriate parameters.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 3 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
My assignment
I have been tasked with attempting to code this program in Java. I've coded a program I think should work, but no matter what I input as the argument it says everyone has heard the rumor in every situation. I think it has something to do with skipping my while loops and me miswriting something else later on...? I'm completely lost, and because my attempts to troubleshoot what is being executed and what isn't have been failing I don't really know how to fix it. My attempt at coding the problem is below. I've tried to put in a lot of notes to help anyone trying to help me follow along, though I'm not sure if I have out everything down in the right etiquette; sorry if I messed up!
public class ProgrammingProblem1 {
public static void main(String[] args) {
int people = Integer.parseInt(args[0]) ;
//Obtains how many people not including Alice are at the party
boolean[] guests;
double averageheard = 0.0;
// This double will be used at the end to determine on average how many people heard the rumor.
double totalheard = 0.0;
// This double is used to help calculate how many people heard the rumor over all the iterations. Keeps track of the total people who knew the rumor throughout the permutations.
double percentsuccess = 0.0;
// This double will be used at the end to determine the percent of how many times the rumor was heard by everyone against how many loops there were.
double rumorsuccess = 0;
// This keeps track of how many times the rumor went all the way around.
double rumorfail = 0;
// This keeps track of how many time the rumor did not make it all the way around.
guests = new boolean[people];
//Fills the array with as many slots as there are people at the party. Guests is the array that stores if someone has heard the rumor or not.
int runtime = Integer.parseInt(args[1]);
// Guests is to figure out how many guests besides Alice are at the party and set them in an array, and Runtime is to figure out how many simulations you are meant to run.
if (people < 1 || runtime < 0){
//This is to check if the arguments were entered correctly.
System.out.println("You entered the arguments incorrectly. The amount of people at the party besides Alice must be at least two and the simulation must be run at least once.");
}else {
for ( int i = 0; i < runtime ; i++) {
// This is for doing however many iterations through are desired.
int heard = 0;
// This variable will be used at the end to determine if everyone has heard the rumor.
int current = 0 ;
// This ensures that we start with our first person ,"Bob", as the progintor of the rumor. Current is whoever is currently telling the rumor to someone else.
for (int l = 0; l < people; l++){
guests[l] = false; }
guests[0] = true ;
// This ensures that Bob already knows the rumor.
int next = (int)(Math.random() * people) ;
// This randomly selects the first person Bob asks about it. Next is the person we are telling the rumor to
while (current == next) {
// This makes sure that the guest we are doing isn't talking to themselves
next = (int)(Math.random() * people );
}
while ( !guests[next] ) {
// This makes the loop go on until the canidate the person it would tell has already heard it
guests[next] = true;
// This line makes whoever was just told the rumor now knows the rumor
int last = current;
// This keeps track of who the last person who said the rumor was
current = next;
// This is making the person we just told the rumor to our new rumor teller.
next = (int)(Math.random() * people);
// This finds a new person to be told the rumor
while (current == next || last == next ){
// This ensures that the person we tell the rumor to next will not be the person telling the rumor to or the person who told them the rumor.
next = (int)(Math.random() * people); }
}
for ( int j = 0; j < people; ++j) {
// This is to determine how many people heard the rumor before it was terminated.
if ( guests[j] == true){
heard = heard + 1;
}
}
if ( heard == people){
//This if statement will add a counter to rumorsuccess if every person was told the rumor, and to rumorfail if everyone didn't hear it.
rumorsuccess = rumorsuccess + 1;
}
else{
rumorfail = rumorfail + 1; }
totalheard = totalheard + heard;
//This is to tally up how many people heard the rumor in total.
}
percentsuccess = (rumorsuccess / (rumorsuccess + rumorfail)) * 100 ;
// This calculates the percent of times the rumor went all the way around to everyone
averageheard = (totalheard / runtime) ;
// This calculates the average amount of times the rumor made its way around
System.out.println("Steven Mikels 20782");
System.out.println("The amount of people in the room besides Alice are: " + people + ". The amount of times the simulation was run is: " + runtime);
System.out.println("The rumor was heard by everyone in the room " + percentsuccess + " percent of the time. The average amount of people who heard the rumor was: " + averageheard);
}
}
}
EDIT 1: I have updated the code to accommodate my updating of the == related error. I have a few new issues now that the code calculates how many people heard on average correctly, though the percentage of times everyone has succeeded doesn't seem to be working. Entering "3" and then any other number into the command line correctly gives 100% of times gone through everyone hears it. Unfortunately, entering any number of people greater than 3 means the code have 0% chance to go all the way around, which is false. Additionally, entering "2" as the first number seems to make the program stall out command prompt. After some testing, it seems the variable rumorfail and rumorsuccess are always equal to each other.
EDIT 2: I'm fairly certain that I've managed to fix my problem; the variables rumorfail and rumorsuccess needed to be a double! It was rounding the number up or down, resulting in the 0% or 100% marks. Unfortunately, I'm still have an issue where my program won't allow two to be the amount of people or else it freaks out. I'm testing for more reasons on why that may be right now, but didn't want people working on the other issue since it is already solved! Strangely, 0 executes the statement correctly and prints that an invalid number has been inputted, but 1 shares the same problem that 2 did.
Off the bat i see a couple typos:
Youre while statement
while ( guests[next] = false ) { is missing a "="
it should be written like this guests[next] == false or !guests[next]
you also did the same thing in this if statement if ( guests[j] = true){
it should be guests[j] == true
The reason for this extra "=" is that "==" is the comparing operator, and "=" is the operator to set something equal to, so when you do if(x=1) your checking wheter not x CAN be set equal to 1, not if it is equal to 1;
Otherwise your code looks like it would run and calculate, just fix these syntax errors.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I am trying to write a Tester and a class that can solve quadratic function.
If you are unfamiliar with quadratic function, or need a reminder, here is a quick link to it's Wikipedia article: http://en.wikipedia.org/wiki/Quadratic_function
My tester seems to work fine, however whenever I try to call the method, the program stops, and it doesn't display the output of the method (which is supposed to display the answer).
I am not skilled enough to find out if the error is within the class or the tester.
Tester:
/**
* A Tester to use to solve quadratic formula. Enter your values
* when prompted, and the answer will be displayed on screen.
*
* #author (Austin C.)
* #version (1.0.0)
*/
import java.io.*;
import java.util.*;
public class C_tester
{
public static void main (String args[])
{
Scanner kb = new Scanner(System.in);
System.out.println ("Enter the coefficents in the form of the following:\n1.A\n2.B\n3.C");
System.out.print("Enter the number for A:");
int a = kb.nextInt();
System.out.print("Enter the number for B:");
int b = kb.nextInt();
System.out.print("Enter the number for C:");
int c = kb.nextInt();
QuadraticFunction.quadratic(a,b,c);
}
}
Quadratic Function Class:
/**
* #Params: you must enter the coefficents, A, B, and C, and the program will calculate them to find the answer
* to a quadratic forumla. coefficents must be integers or doubles.
*
* #author (Austin C.)
* #version (1.0.0)
*/
public class QuadraticFunction
{
public void QuadraticFunction()
{
}
public static double quadratic(double a, double b, double c)
{
double topPos;
double topNeg;
double bot;
topPos = -b + Math.sqrt(Math.pow(b,2.0) - 4 * a * c);
topNeg = -b - Math.sqrt(Math.pow(b,2.0) - 4 * a * c);
bot = 2*a;
double ansPos = topPos/bot;
double ansNeg = topNeg/bot;
return ansPos + ansNeg;
}
}
Any help to find the error myself or find it for me is greatly appreciated. Also, if you find a more efficient way to do this, please share! I am always looking for more efficient ways to write code.
If the question is unclear, please say so and I can redo it in a more understandable way.
quadratic has return type double, and there are no print statements in the method. What this means is that it should return a value, but there is no reason that value should be printed. You can fix this by assigning the function result to a variable, and then adding a statement to print it to screen, like so:
double answer = QuadraticFunction.quadratic(a,b,c);
System.out.println(answer);
Also, you should note that a quadratic equation can have 2 real roots (possibly both the same), so you should be returning an array of doubles rather than a single double which is the sum of those 2 roots.
What do you expect it to print? You never tell the program to print anything. You can have it print the result to stdout by changing the last line in the tester to System.out.println(QuadraticFunction.quadratic(a,b,c)); if the program stops and there was no stack trace printed it means that it was executed succesfully
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Hello to all and best wishes for 2014.
My question is ... In the following program is it possible to replace the ht = Clavier.lireDouble () to simplify the package because every time I implement this command I have to create a class "Clavier.java "this increased the source code ?
Thank you for your answers
best regards
NOTE FROM EDITOR
Clavier is the French translation of keyboard. The Clavier class seems
to be used for educational purpose. The question asked here could be
"How can my java program read a value from the keyboard input?"
Billing program for lectuire a price exclusive of tax and VAT calculation and VAT and price discounts based on cost
r0%
1000 <= r1%
2000 <= r3%
r5%> = $ 5000 */
/Program (In french)/
public class Tva
{
public static void main (String[]args)
{
double ht;
double ttc, net, tauxr, remise;
double taux_tva = 21.6;
System.out.print ("donnez le prix hors taxe :");
ht = Clavier.lireDouble(); /*Replace this command*/
ttc = ht * (1. + taux_tva/100);
if (ttc < 1000.) tauxr = 0;
else if (ttc < 2000) tauxr = 1.;
else if (ttc < 5000) tauxr = 3.;
else tauxr = 5.;
remise = ttc * tauxr / 1000;
net = ttc - remise;
System.out.println ("Prix Ttc : "+ ttc);
System.out.println ("Remise : "+ remise);
System.out.println ("Net à payer : "+ net);
}
}
You can use the Scanner class for that purpose.
You code to replace can become
Scanner scan = new Scanner(System.in);
ht = scan.nextDouble();
One remark : my mother tongue is also French but IMHO I think it is better to code in English because it is always possible that you will have to share/submit... your code to people who don't understand your mother tongue so it will make things more difficult.
Ah I was about to forget it : because Clavier is a French word, you can be sure it never existed in Java or standard JDK.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I was asked in an interview to implement a business rule
Requirements change. They always do:
assess a 20% fee for any amount below $100,000.
assess a 10% fee for any amount between $100,000 and $500,000.
assess a 5% fee for any amount above $500,000
Calculate the fee for an arbitrary amount x.
Example: Given a $600,000 invoice the fee should be $65,000.
Given a $50,000 invoice the fee should be $10,000.
Given a $200,000 invoice the fee should be $30,000.
I used CofR but the interviewer then asked what if their is more than 3 conditions like n of them would i create n-classes to handle each request.
Is their a better approach to the question asides writing a very long recursive function checking for each of the conditions.
CoR is helpful when the members of the chain have substantially different rules, but in this case, all of the rules are basically the same (charge a certain percent if the amount is over X). Instead of independent classes, just have one struct-like class that holds the minimum amount and percentage, and another one that looks up the appropriate fee:
class FeeSchedule {
static class Entry implements Comparable<Entry> {
int threshold;
int percentage;
int compareTo(Entry other) {
// sort by percentage, descending
}
SortedSet<Entry> feeTable;
int calculateFee(int invoiceAmount) {
for(Entry e : feeTable)
if(invoiceAmount > e.threshold)
return (invoiceAmount * e.percentage);
// error condition; return 0?
}
}
I would guess that the interviewer was implying that something like the chain-of-responsibility pattern would be a little over-engineered for a problem like this. There's also an argument that your implementing classes would actually have the same responsibility, in that they'd all be computing an amount based on a given input, just with different parameters.
I would probably do this with two simple classes. One would compute the percentage fee rate based on the input value and one would use this rate to return the fee amount.
If you need to add a fourth condition, you just add it to the class containing the rate computation. I don't see why it needs to be any more complicated than this for such a simple problem.
EDIT:
I was thinking along the same lines as #chrylis in that there'd be a class to perform the calculation by processing an ordered list of rates.
class Rate {
int rangeSize;
double commission;
Rate(int rangeSize, double commission){
this.rangeSize = rangeSize;
this.commission = commission;
}
int computeForAmount(int amount) {
if (amount <= 0) {
return 0;
}
return (int) (Math.min(amount, this.rangeSize) * this.commission);
}
}
class FeeCalculator {
List<Rate> rates = Arrays.asList(
new Rate(100, 0.2),
new Rate(400, 0.1),
new Rate(500, 0.05));
int calculateCommission(int startingAmount) {
int commission = 0;
int remainingAmount = startingAmount;
for (Rate rate : this.rates) {
commission += rate.computeForAmount(remainingAmount);
remainingAmount -= rate.rangeSize;
}
return commission;
}
}
I admit that I'm not entirely happy about breaking the encapsulation by calling rate.rangeSize but it does demonstrate the design I was trying to articulate.
I think a simple strategy pattern should be enough in this case. Something like:
interface FeeAssessor {
public double assessFee(double invoice);
}
FeeAssessor feeAssessor = new FeeAssessor() {
// logic goes here
};
double calculateFee(double invoice) {
return feeAssessor.assessFee(invoice);
}
For a simple business logic that you presented, I think it would be simpler to implement it all inside one assessFee() function. You can implement different (simple) ones and swap out the "strategy" object as needed. If the fee assessment algorithm depends on multiple varying factors that are independent of each other, then you can further split them up into multiple strategy methods.