So I have the following code
for (int i = 0; i <= numberOfTickets; i++)
{
System.out.println("Please enter your age or if you are a student enter -1");
int age = input.nextInt();
if ((age < 10) && (age > 0))
{
cost = (cost / 4);
}
else if ((age < 16) && (age >= 10))
{
cost = (cost / 2);
}
else if (age > 60)
{
cost = (cost / 2.5);
}
else if (age == -1)
{
cost = (cost / (4/3));
}
System.out.println(cost);
}
the problem is say that initially the cost is £10 and the user enters an age of 12 I want the value of £5 to be saved as say int ticketCost1 before continuing the for loop but starting with 10 again.
In essence i want to at the end of the loop have all the costs of the tickets with the individual discounts applied and to be then able to dd them all together and have a final cost.
P.S. I intend to add more so that for every child i.e. age 0 to 10 then they go free with anyone over the age of 16.
In java.
Make a new double, for now lets call it sum. Now instead of writing:
cost = (cost/whatever);
do this:
sum+= (cost/whatever);
now you save all them in 1 number summed, and cost stays as 10; while all the discounts are applied. Just make sure you initialize sum to 0 OUTSIDE and before the for loop
If I understand you correctly, you have a group of people of varying ages, and you want to find the total cost of all the tickets purchased by the group. You can have two lists, then: one to store the ages, and one to store the ticket costs. The cost of the group will be the total cost stored in the second list.
static final TICKET_PRICE = 10;
int getTotalCost(List<Integer> ages) { // populated list of ages
List<Integer> costs = new ArrayList<>();
for (int i : ages)
costs.add(getTicketPrice(int age));
int totalCost = 0;
for (int curr_cost : costs)
totalCost += curr_cost;
return totalCost;
}
int getTicketPrice(int age) {
int price;
if (age > 60) price = TICKET_PRICE/2.5;
... // all the other conditions, e.g. for students, children under 10, etc.
else price = TICKET_PRICE; // if no special condition applies
return price;
}
For the more complicated conditions (e.g. a child under 10 goes free with another person over the age of 16), it's best if you have a separate method to compute the total cost. Keep in mind that as you increase these conditions that depend not just on the individual, but on the age-distribution of the whole group, the optimal cost computation will start to resemble quite a complex problem in and of itself.
Related
I am trying to create a method so that if the user enters a number of cents over 99, the updateMoney method will add dollars accordingly and then place the extra change once the cents goes under 100.
public void updateMoney(int cent) {
int addDollars = 0;
int change = 0;
if (cent > 99) {
for(int i = cent; i > 99; i -= 100)
{
addDollars += 1;
cent -= 100;
}
}
this.dollars = dollars + addDollars;
this.cents = cent;
}
public Money(int dol, int cent) {
if (cent < 0 || dol < 0) {
System.out.println("Invalid amount entered");
} else {
if (cent > 99) {
updateMoney(cent);
}
this.dollars = dol;
this.cents = cent;
}
}
This is the code I am currently working with.
I had originally tried a different method that ended up not working so I tried doing something like this instead but my outputs are still off.
In my driver I ran
Money money = new Money(15, 300); and the output was $15.00 when it should end up being $18.99
You should consider storing your dollars and cents in one long value. The following code takes your dollars and cents, combines them, adds the user's inputted cents correctly, and splits them up in dollars and cents again. But why not just keep them together all the time?
long dollarsWithCents = dollars * 100 + cents;
dollarsWithCents += parsedUserInput;
cents = dollarsWithCents % 100;
dollars = dollarsWithCents / 100;
I am using arrays for a programming project due tonight. I am able to add up all the numbers of the array, but from there I am unable to remove the maximum and minimum values from it. My attempt and the actual project description is below...
In the sport of diving, seven judges award a score between 0 and 10, where each score may be a floating-point value. The highest and lowest scores are thrown out and the remaining scores are added together. The sum is then multiplied by the degree of difficulty for that dive. The degree of difficulty ranges from 1.2 to 3.8 points. The total is then multiplied by 0.6 to determine the diver’s score.
Write a computer program that inputs a degree of difficulty and seven judges’ scores and outputs the overall score for that dive. The program should ensure that all inputs are within the allowable data ranges.
package baker;
import java.util.Scanner;
public class DiveScoreDriver {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
double total = 0;
double totalFinal = 0;
double divingScores[] = new double[7];
double input;
double difficultyInput = 0;
double minimum = divingScores[0];
double maximum = divingScores[0];
for (int i = 1; i < divingScores.length + 1; i++)
{
System.out.println("Judge " + i + " please enter your score.");
input = keyboard.nextDouble();
System.out.println();
if(input < 0 || input > 10)
{
System.out.println("Invalid Score");
return;
}
else
{
total += input;
}
}
while (difficultyInput < 1.2 || difficultyInput > 3.8)
{
System.out.println("Difficulty Rating: ");
difficultyInput = keyboard.nextDouble();
}
for(int i = 0; i < divingScores.length; i++)
{
if(divingScores[i] < minimum)
minimum = divingScores[i];
if(divingScores[i] > maximum)
maximum = divingScores[i];
}
total = total - maximum - minimum;
total = total * difficultyInput;
total = total * 0.6;
System.out.printf("\nThe overall score for the dive: %.1f\n", total);
}
}
The portion in particular that I am struggling with is here:
for(int i = 0; i < divingScores.length; i++)
{
if(divingScores[i] < minimum)
minimum = divingScores[i];
if(divingScores[i] > maximum)
maximum = divingScores[i];
}
total = total - maximum - minimum;
total = total * difficultyInput;
total = total * 0.6;
The code runs and produces a correct output, but it does not seem to subtract the max and min values and the problem requests... Thanks for the help!
You have forgotten to add each judge's score to the array divingScores. You can fix this by changing the first for loop to the following:
for (int i = 0; i < divingScores.length; i++)
{
System.out.println("Judge " + (i + 1) + " please enter your score.");
input = keyboard.nextDouble();
System.out.println();
if(input < 0 || input > 10)
{
System.out.println("Invalid Score");
return;
}
else
{
total += input;
divingScores[i] = input;
}
}
You should also initialize minimum as:
minimum = 0
If you do not, every score above 0 will not be considered for the minimum.
You never set the array values in the else branch within your for loop, it should look like this:
if(input < 0 || input > 10) {
System.out.println("Invalid Score");
return;
} else {
divingScores[i] = input;
total += input;
}
Before the second loop, you can use Java 8 functional programming to get the minimum and maximum like this, which is shorter:
double minimum = Arrays.stream(divingScores).min().getAsDouble();
double maximum = Arrays.stream(divingScores).max().getAsDouble();
Alternatively, you should initialize the minimum and maximum values properly, one way to do this in general for at least one element in the array is:
double minimum = Double.MAX_VALUE; // Use your maximum in your case
double maximum = Double.MIN_VALUE; // Use your minimum in your case
You can sort the array and then add the array elements except first and last element of sorted array which will automatically remove the minimum and maximum
Arrays.sort(divingScores);
double ans=0;
for(int i=1;i<divingScores.length-1;i++){
System.out.println(divingScores[i]);
ans+=divingScores[i];
}
I am trying to make a simple java program, that calculates how much tickets would cost.
1 adult ticket is 10$, a child cost 5$ but a family ticket (2 adults and 2 children) is 26$. An obvious saving
So when input from the user, it needs to calculate how many family tickets (if applicable) and then pricing of items if they dont fit into a family bundle.
I.e.
Number of adults: 2
Number of children: 4
Number of family tickets: 1
Number of child tickets: 2
Total cost: $36
I cannot figure out the logic behind getting the pairings, comparing and taking out the extra items from both adults and children if needed. Here is what ive gotten so far:
double adultPairs,childPairs;
if (numberAdults <= 1) {
adultPairs = 0;
}
else if (isEven(numberAdults)) {
adultPairs = numberAdults / 2;
adultTickets = 0;
}
else {
adultPairs = numberAdults / 2;
adultTickets = 1;
}
if (numberChildren <= 1) {
childPairs = 0;
}
else if (isEven(numberChildren)) {
childPairs = numberChildren / 2;
childTickets = 0;
}
else {
childPairs = numberChildren / 2;
childTickets = 1;
}
What about this one?
int familyTickets = Math.min(adults/2, childs/2);
int adultTickets = adults - familyTickets*2;
int childTickets = childs - familyTickets*2;
First line compares the half of adults and childs (rounded down) and returns the minimum value of it. For example, if you have 9 adults and 25 children, it takes 9/2 and 25/2 which is 4 and 12, therefore it returns 4. And thats how much family tickets you want.
In next two lines, you just takes all adults/children and substract the adults/children family tickets, which is number of family tickets multiplied by two.
Even without Math.min method, it is quite easy :
int familyTickets = 0;
if (adults > childs){
familyTickets = childs/2;
} else {
familyTickets = adults/2;
}
int adultTickets = adults - familyTickets*2;
int childTickets = childs - familyTickets*2;
PS : Also note, that in Java, if you divide integer with integer, it returns another integer "rounded" down (it is not technically rounded, it just cut off anything less than 1) and it is what we need here. This is reason why I do not use double.
i am working on a Mock Test and i am struggling to create a loop that will cycle the input 12 times while adding each input to a sum.
Determines the average weight of a person over a particular year.
For each month, your algorithm should input the person's weight for that month (a positive real number). Your algorithm should loop,
repeating the input, until the input is positive.
Finally, your algorithm output the average weight.
After looking through lecture notes on Iteration Control Structures i have come up with this:
public static void main (String [] args)
{
double month, sum;
sum = 0;
for (month = 1; month <= 12; month++)
{
month = ConsoleInput.readDouble("Enter weight for each month");
sum += month;
}
System.out.println("Sum total is: " +sum);
}
Unfortunately all this does for me is repeat the input an infinite amount of times until i enter a number greater than 12.
I just want to make ConsoleInput cycle 12 times. Does anyone know the best way about this using while, do-while and for loops? I'm not allowed to use arrays, objects etc at this point in the course.
Any advice is appreciated cheers.
You can Possibly do the Following in order to make your Program Work.Just add one more variable monthweight and assign the user input
public static void main (String [] args)
{
double month, sum,monthweight;
sum = 0;
for (month = 1; month <= 12; month++)
{
monthweight = ConsoleInput.readDouble("Enter weight for each month");
if(monthweight > 0.0M)
{
sum += monthweight;
}
else
{
break;
}
}
System.out.println("Sum total is: " +sum);
}
You're using month in 2 ways, both to count to 12 and to receive the person's weight in. I think if you would assign ConsoleInput.readDouble(..) to another variable, and add that to the sum, your program will work better.
So I'm trying to make a program where it averages out your golf scores. I edited a standard averaging calculator to make it work:
import java.util.Scanner;
public class Test {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
int total = 0;
int score;
int average;
int counter = 0;
while (counter >= 0){
score = input.nextInt();
total = total + score;
counter++;
}
average= total/10;
System.out.println("Your average score is "+ average);
}
}
But when I enter scores, I can keep entering infinite scores and it never averages them. It just keeps expecting another score. I know it has something to do with this line:
while (counter >= 0){
but I'm not sure what to do so it works right.
You never find a way to break out of the loop:
while (counter >= 0){
score = input.nextInt();
total = total + score;
counter++;
}
will loop 2 billion times (no I'm not exaggerating) since you don't have another way to break out.
What you probably want is to change your loop condition to this:
int score = 0;
while (score >= 0){
This will break out when a negative score is entered.
Also, you have an integer division at the end. You want to make floating-point, so change the declaration to this:
double average;
and change this line to this:
average = (double)total / 10.;
You need some way to beak out of the loop. For example, entering -1:
int score = input.nextInt();
if (score < 0) { break; }
total += score;
You also seem to have a couple of errors in the calculation of the average:
Don't always divide by 10 - use the value of counter.
Use floating point arithmetic. If you need an int, you probably want to round to nearest rather than truncate.
For example:
float average = total / (float)counter;
You have to specify the counter value, the default value is 0, so the condition in the while is always true, so you will go in an infinite loop.
while (true) {
score = input.nextInt();
if (score == 0) {
break;
}
total = total + score;
counter++;
}
Now your program will realize you're done entering scores when you enter the impossible score 0.