I\'m trying to make a double work here but I\'m not sure what I\'m doing wrong.
ID: 3857068 • Letter: I
Question
I'm trying to make a double work here but I'm not sure what I'm doing wrong. I can't get floating points to work. Please help.
The output should be something like this:
But my output is this:
run:
Party Size Cost Estimate Per Person
2 70
4 45
6 34
8 30
10 28
12 24
14 23
16 21
18 20
20 20
BUILD SUCCESSFUL (total time: 0 seconds)
---------------------------------------------------------------
//trying to put double
package costestimate;
public class CostEstimate {
static int cost (int numberofPeople) {
final int RENTAL = 100;
double foodCost = 0.0;
double costPerPerson;
if (numberofPeople >=1 && numberofPeople <=5)
foodCost = 20;
else if (numberofPeople >=6 && numberofPeople <=10)
foodCost = 18;
else if (numberofPeople >=11&& numberofPeople <=15)
foodCost = 16;
else if (numberofPeople >15)
foodCost = 15;
return costPerPerson = ((foodCost * numberofPeople)+RENTAL)/numberofPeople;
}
public static void main (String args[]) {
System.out.println("Party Size Cost Estimate Per Person");
for (int i=2; i<=20; i=i+2){
System.out.printf( "%d %d%n", i, cost(i));
}
}
}
Party Size (#people) Cost Estimate Per Person $70.00 $45.00 $34.67 $30.50 $28.00 $24.33 4 10 12 20 $20.00Explanation / Answer
I had modified the code . So that , you get the required output.USE System.out.println() instead of System.out.printf().And, you have to return a double value from the function.And,you to divide with a double value in order to get a double data type result.I have made the modified part in BOLD format
Code:-
public class HelloWorld{
static double cost (int numberofPeople) {
final int RENTAL = 100;
double foodCost = 0.0;
double costPerPerson;
if (numberofPeople >=1 && numberofPeople <=5)
foodCost = 20;
else if (numberofPeople >=6 && numberofPeople <=10)
foodCost = 18;
else if (numberofPeople >=11&& numberofPeople <=15)
foodCost = 16;
else if (numberofPeople >15)
foodCost = 15;
return costPerPerson = ((foodCost * numberofPeople)+RENTAL)/(double)numberofPeople;
}
public static void main (String args[]) {
System.out.println("Party Size Cost Estimate Per Person");
for (int i=2; i<=20; i=i+2){
System.out.println(i+" "+cost(i));
}
}
}