My totals are not adding up, but just staying as 0 - loops

Whenever I run my code, all my totals end up as just zero. What am I missing?
while (theaterNumber != -999)
childTicketInOneTotal += childTicketInOne;
adultTicketInOneTotal += adultTicketInOne;
childTicketInTwoTotal += childTicketInTwo;
adultTicketInTwoTotal += adultTicketInTwo;
if (theaterNumber == 1)
{System.out.print("How many child tickets were sold?");
childTicketInOne = keyboard.nextInt();
System.out.print("How many adult tickets were sold?");
adultTicketInOne = keyboard.nextInt();
System.out.print("Which theater was used (1 or 2)? Enter -999 to complete inputs.");
theaterNumber = keyboard.nextInt();}
else if (theaterNumber == 2)
{System.out.print("How many child tickets were sold?");
childTicketInTwo = keyboard.nextInt();
System.out.print("How many adult tickets were sold?");
adultTicketInTwo = keyboard.nextInt();
System.out.print("Which theater was used (1 or 2)? Enter -999 to complete inputs.");
theaterNumber = keyboard.nextInt();}}
//Display totals
System.out.println();
System.out.println("Theater 1 Totals:");
System.out.println("Adult Tickets Sold: "+ adultTicketInOneTotal +"");
System.out.println("Child Tickets Sold: "+ childTicketInOneTotal +"");
System.out.printf("Total Amount Made: $%.2f \n\n", totalAmountTheaterOne);
System.out.println();
System.out.println("Theater 2 Totals:");
System.out.println("Adult Tickets Sold: "+ adultTicketInTwoTotal +"");
System.out.println("Child Tickets Sold: "+ childTicketInTwoTotal +"");
System.out.printf("Total Amount Made: $%.2f \n\n", totalAmountTheaterTwo);
}}

What language is this? You probably want to initialize your variables before the loop starts and add the input before the output, something like this:
childTicketInOneTotal = 0;
adultTicketInOneTotal = 0;
childTicketInTwoTotal = 0;
adultTicketInTwoTotal = 0;
while (theaterNumber != -999){
if (theaterNumber == 1)
{System.out.print("How many child tickets were sold?");
childTicketInOne = keyboard.nextInt();
System.out.print("How many adult tickets were sold?");
adultTicketInOne = keyboard.nextInt();
System.out.print("Which theater was used (1 or 2)? Enter -999 to complete inputs.");
theaterNumber = keyboard.nextInt();}
else if (theaterNumber == 2)
{System.out.print("How many child tickets were sold?");
childTicketInTwo = keyboard.nextInt();
System.out.print("How many adult tickets were sold?");
adultTicketInTwo = keyboard.nextInt();
# end if not needed?
System.out.print("Which theater was used (1 or 2)? Enter -999 to complete inputs.");
theaterNumber = keyboard.nextInt();}}
childTicketInOneTotal += childTicketInOne;
adultTicketInOneTotal += adultTicketInOne;
childTicketInTwoTotal += childTicketInTwo;
adultTicketInTwoTotal += adultTicketInTwo;
//Display totals
System.out.println();
System.out.println("Theater 1 Totals:");
System.out.println("Adult Tickets Sold: "+ adultTicketInOneTotal +"");
System.out.println("Child Tickets Sold: "+ childTicketInOneTotal +"");
System.out.printf("Total Amount Made: $%.2f \n\n", totalAmountTheaterOne);
System.out.println();
System.out.println("Theater 2 Totals:");
System.out.println("Adult Tickets Sold: "+ adultTicketInTwoTotal +"");
System.out.println("Child Tickets Sold: "+ childTicketInTwoTotal +"");
System.out.printf("Total Amount Made: $%.2f \n\n", totalAmountTheaterTwo);
}}

Related

how to use map in Go

I want to make a simple program to count debt installments. The requirements are:
Input the debt value
Input how long the installments
The first half of the installment bank interest is 11% and the rest are 8%
Must use maps
Here's my code
package main
import "fmt"
func main() {
fmt.Print("Input the debt value : ")
var debt int
fmt.Scanln(&debt)
fmt.Print("Input how long the installments : ")
var installment int
fmt.Scanln(&installment)
fmt.Println("====================================================")
fmt.Println("Total debt : ", debt)
fmt.Println("Installments : ", installment)
fmt.Println("====================================================")
var firstHalf = installment / 2
var pay int
for i := 1; i <= installment; i++ {
value := map[string]int{
"month": i,
"payment": pay,
}
if i <= firstHalf {
pay = (debt / installment) + (debt * 11 / 100)
fmt.Println(value["month"],"Installment with bank interest (11%) is", value["payment"])
} else {
pay = (debt / installment) + (debt * 8 / 100)
fmt.Println(value["month"],"Installment with bank interest (8%) is", value["payment"])
}
}
}
If I run the code and for example :
The debt is 10.000.000
The installments are 7 months
Here's the output :
1 Installment with bank interest (11%) is 0
2 Installment with bank interest (11%) is 2528571
3 Installment with bank interest (11%) is 2528571
4 Installment with bank interest (8%) is 2528571
5 Installment with bank interest (8%) is 2228571
6 Installment with bank interest (8%) is 2228571
7 Installment with bank interest (8%) is 2228571
I don't know why the first index is always 0, even the next calculation is right. So, I guess that either I am using the wrong syntax or I am trying to do something that can not be done. Maybe most likely experienced people will see right away what is wrong.
if i <= firstHalf {
pay = (debt / installment) + (debt * 11 / 100)
value["payment"] = pay
fmt.Println(value["month"],"Installment with bank interest (11%) is",
value["payment"])
} else {
pay = (debt / installment) + (debt * 8 / 100)
value["payment"] = pay
fmt.Println(value["month"],"Installment with bank interest (8%) is",
value["payment"])
}
It is printing the the payment value of map as 0 because it is assigned with pay which has no value initially.You can fix this by declaring the map beneath the if else condition and then print your values,here is the modified code for the same logic:
package main
import "fmt"
func main() {
fmt.Print("Input the debt value : ")
var debt int
fmt.Scanln(&debt)
fmt.Print("Input how long the installments : ")
var installment int
fmt.Scanln(&installment)
fmt.Println("====================================================")
fmt.Println("Total debt : ", debt)
fmt.Println("Installments : ", installment)
fmt.Println("====================================================")
var firstHalf = installment / 2
var pay int
for i := 1; i <= installment; i++ {
if i <= firstHalf {
pay = (debt / installment) + (debt * 11 / 100)
} else {
pay = (debt / installment) + (debt * 8 / 100)
}
value := map[string]int{
"month": i,
"payment": pay,
}
if i <= firstHalf {
fmt.Println(value["month"], "Installment with bank interest (11%) is", value["payment"])
} else {
fmt.Println(value["month"], "Installment with bank interest (8%) is", value["payment"])
}
}
}
Output:
Input the debt value : 1000
Input how long the installments : 5
====================================================
Total debt : 1000
Installments : 5
====================================================
1 Installment with bank interest (11%) is 310
2 Installment with bank interest (11%) is 310
3 Installment with bank interest (8%) is 280
4 Installment with bank interest (8%) is 280
5 Installment with bank interest (8%) is 280

How to find the index of a value in an array and use it to display a value in another array with the same index

I am new to Python and I have been stuck trying out a "simple banking program".
I have got everything right except for this bit:
If the user types S then:
Ask the user for the account number.
Search the array for that account number and find its position in the accountnumbers array.
Display the Name, and balance at the position found during the above search.
Originally it was just supposed to be through accounts 1-5, but now I am having trouble coming up with a way to search the account numbers if they are any number, not just 1 - 5. For example
The user makes his account numbers 34, 445, 340,2354 and 3245. Completely random account numbers with no order.
Here is what I have so far
names = []
accountNumbers = []
balance = []
def displaymenu():
print("**** MENU OPTIONS ****")
print("Type P to populate accounts")
print("Type S to search for account")
print("Type E to exit")
choiceInput()
def choiceInput():
choice = str(input("Please enter your choice: "))
if (choice == "P"):
populateAccount()
elif (choice == "S"):
accountNumb = int(input("Please enter the account number to search: "))
if (accountNumb > 0) and (accountNumb < 6):
print("Name is: " + str(names[accountNumb - 1]))
print(names[accountNumb - 1] + " account has the balance of : $" + str(balance[accountNumb -1]))
elif (accountNumb == accountNumbers):
index = names.index(accountNumb)
accountNumb = index
print(names[accountNumb - 1] + " account has the balance of : $" + str(balance[accountNumb -1]))
else:
print("The account number not found!")
elif (choice == "E"):
print("Thank you for using the program.")
print("Bye")
raise SystemExit
else:
print("Invalid choice. Please try again!")
displaymenu()
def populateAccount ():
name = 0
for name in range(5):
Names = str(input("Please enter a name: "))
names.append(Names)
account ()
name = name + 1
def account ():
accountNumber = int(input("Please enter an account number: "))
accountNumbers.append(accountNumbers)
balances()
def balances ():
balances = int(input("Please enter a balance: "))
balance.append(balances)
displaymenu()
I have tried to use indexes and have not been able to find a solution.
Replace the following line of code
if (accountNumb > 0) and (accountNumb < 6):
with
if (accountNumb > 0) and (accountNumb < len(accountNumbers)):
My mistake. I messed up when appending the account number:
def account ():
accountNumber = int(input("Please enter an account number: "))
accountNumbers.append(accountNumbers)
balances()
I appended
accountNumbers
not
accountNumber
the code should be
def account ():
accountNumber = int(input("Please enter an account number: "))
accountNumbers.append(accountNumber)
balances()
also the searchArray function I made was:
def searchArray(accountNumbers):
x = int(input("Please enter an account number to search: "))
y = accountNumbers.index(x)
print("Name is: " + str(names[y]))
print(str(names[y]) + " account has a balance of: " + str(balance[y]))
rookie mistake , shouldnt be using such similar object names.

How to create a For Loop in cplex

I am new to cplex.
I would like to implement a loop for my MILP problem. It's about to add up.
For example like this:
time: 1 2 3 4
weight: 10 20 30 40
The solution should tell me the Summation weight at each time;
time: 1 2 3 4
sum_weight: 10 30 60 100
I hope my problem becomes clear.
It sounds like you want to use IBM ILOG Script (i.e., JavaScript). For example, the foodmanufact example has the following execute block at the end:
execute DISPLAY {
writeln(" Maximum profit = " , cplex.getObjValue());
for (var i in Months) {
writeln(" Month ", i, " ");
write(" . Buy ");
for (var p in Products)
write(Buy[i][p], "\t ");
writeln();
write(" . Use ");
for (p in Products)
write(Use[i][p], "\t ");
writeln();
write(" . store ");
for (p in Products)
write(Store[i][p], "\t ");
writeln();
}
}
This can be modified to show the sum of Buy over products, like so:
execute DISPLAY {
writeln(" Maximum profit = " , cplex.getObjValue());
for (var i in Months) {
writeln(" Month ", i, " ");
write(" . Buy ");
for (var p in Products)
write(Buy[i][p], "\t ");
writeln();
// START: Display the sum of Buy over products:
write(" . Sum(Buy) ");
var sumBuy = 0;
for (var p in Products) {
sumBuy += Buy[i][p];
write(sumBuy, "\t ");
}
writeln();
// END
write(" . Use ");
for (p in Products)
write(Use[i][p], "\t ");
writeln();
write(" . store ");
for (p in Products)
write(Store[i][p], "\t ");
writeln();
}
}
This gives output, like the following:
Maximum profit = 100278.703703704
...
Month 6
. Buy 480.37037037 629.62962963 0 730 0
. Sum(Buy) 480.37037037 1110 1110 1840 1840
. Use 0 200 0 230 20
. store 500 500 500 500 500

Insights on approaching fare calculations

Basically I'm attempting a question on how to compute fee. However, my code is extremely long. I ended up using a heck tons of 'if' and 'else' for my code. I was wondering if there is any better way on approaching this question.
I initially attempted to use loops to keep stacking the fee but I face a problem when my time cross the critical juncture. I added time to TimeIn along with my fees, but as it crosses the 7am mark, I need to reset it back to 7am so that my fees will be charge properly. And that was when I gave up when my code became very long too.
Eg. loop adds from 0630 to 0730, fees are properly increased, the first 30 minutes of 0700 will be skipped and fees are wrongly charged.
The question I attempted:
Mr. Wu has been going to work every day by taxi for many years. However, the taxi fare has been increasing rather quickly in recent years. Therefore, he is considering driving to work instead.
One of the costs for driving is the parking fee. The parking rates of the car park at Mr. Wu’s workplace are as shown in the table below.
Weekday Saturday Sunday
4am ~ 7am $2.00 per hour $2.50 per hour $5
7am ~ 6pm $1.20 per 30 minute $1.50 per 30 minutes per
6pm ~ midnight $5.00 per entry $7.00 per entry entry
Special note:
1. The car park opens at 4am and closes at midnight. All vehicles must leave
by midnight.
2. There is a grace period of 10 minutes on any day (i.e., it is completely
free to park for 10 minutes or less regardless of day and time.)
3. There is a 10% surcharge for parking more than 10 hours on a weekday and
20% for Saturday. There is no surcharge for Sunday.
4. There is an additional $3.00 fee for exiting after 10pm on any day.
(Surcharge is not applicable on this fee.)
Your program should read in one integer, which is an integer between 1 and 7
representing the day of the week (1 being Monday and 7 being Sunday). It should also
read in two numbers representing the time-in and time-out in 24-hour format. It
should then calculate and display the parking fee (with two decimal places).
You may assume that the inputs are valid (i.e., the day is within the specified range,
both time-in and time-out are between 4am and midnight in 24-hour format, and timeout
is no earlier than time-in).
My extremely long code:
#include <stdio.h>
#include <math.h>
double computeFee(int, int, int);
int main(void){
int day, timeIn, timeOut;
scanf("%d %d %d", &day, &timeIn, &timeOut);
printf("Enter day: %d\n", day);
printf("Enter time-in: %d\n", timeIn);
printf("Enter time-out: %d\n", timeOut);
printf("Parking fee is $%.2lf\n", computeFee(day, timeIn, timeOut));
return 0;
}
double computeFee(int day, int timeIn, int timeOut){
double fee = 0;
double TimeIn, TimeOut;
TimeIn = 60*(floor(timeIn/100)) + (timeIn%100);
TimeOut = (60*(floor(timeOut/100)) + (timeOut%100));
if((day>=1)&&(day<=5)){
if(TimeIn<420){
if(TimeOut<420){
fee += 2*ceil((TimeOut - TimeIn)/60);
}
else{
fee += 6;
if(TimeOut>=1080){
fee += 31.4;
}
else{
fee += 1.2*ceil((TimeOut - 420)/30);
}
}
}
if(TimeIn>=420){
if(TimeIn>=1080){
fee = 5;
}
else{
if(TimeOut>=1080){
fee += (1.2*ceil((1080 - TimeIn)/30) + 5);
}
else{
fee += (1.2*ceil((TimeOut - TimeIn)/30));
}
}
}
if((TimeOut-TimeIn)>=600){
fee *= 1.1;
}
}
if(day == 6){
if(TimeIn<420){
if(TimeOut<420){
fee += (2.5*ceil((TimeOut - TimeIn)/60));
}
else{
fee += 7.5;
if(TimeOut>=1080){
fee += 40;
}
else{
fee += (1.5*ceil((TimeOut - 420)/30));
}
}
}
if(TimeIn>=420){
if(TimeIn>=1080){
fee = 7;
}
else{
if(TimeOut>=1080){
fee += (1.5*ceil((1080 - TimeIn)/30) + 7);
}
else{
fee += (1.5*ceil((TimeOut - TimeIn)/30));
}
}
}
if((TimeOut-TimeIn)>=600){
fee *= 1.2;
}
}
if(day == 7){
fee = 5;
}
if((timeOut/100)>=22){
fee += 3;
}
if((timeOut - timeIn)<=10){
fee = 0;
}
return fee;
}
Examples on how fees are calculated:
Example 1: Tuesday, 4:29am to 7:50am.
• 4:29am to 7am is charged as 3 1-hour slots: $2.00 * 3 = $6.00
• 7am to 7:50am is charged as 2 30-minute slots: $1.20 * 2 = $2.40
• Total fee = $6.00 + $2.40 = $8.40
Example 2: Saturday, 7:01am to 7:49pm.
• 7:01am to 6pm is charged as 22 30-minute slots: $1.50 * 22 = $33.00
• 6pm to 7:49pm is charged as one entry: $7.00
• 20% Surcharge for parking more than 10 hours: ($33.00 + $7.00) * 20% =
$8.00
• Total fee = $33.00 + $7.00 + $8.00 = $48.00
Example 3: Sunday, 3pm to 10:01pm.
• 3pm to 10:01pm is charged as one entry: $5.00
• Additional fee for exiting after 10pm: $3.00
• Total fee = $5.00 + $3.00 = $8.00
Example 4: Thursday, 11:49pm to 11:59pm.
• Grace period
• Total fee = $0.00
Example 5: Monday, 12pm to 10:01pm.
• 12pm to 6pm is charged as 12 30-minute slots: $1.20 * 12 = $14.40
• 6pm to 10:01pm is charged as one entry: $5.00
• 10% Surcharge for parking more than 10 hours: ($14.40 + $5.00) * 10% =
$1.94
• Additional fee for exiting after 10pm: $3.00
• Total fee = $14.40 + $5.00 + $1.94 + $3.00 = $24.34
Thanks for reading my long question. And thanks in advance for the help.
note: I havent learn arrays and anything beyond that. Only learn loops and selection statement so far(reading K&R programming tutorial, until chapter 17, using Online GeekforGeek as compiler). However, I will still greatly appreciate solutions using other methods.

Find highest earning company from while loop

I need to find the company with the highest earnings.
So far I am able to pull out the highest total Earnings from the loop but have no idea how to get the company name that ties with this highest earnings.
while( count <= noOfComp)
{
System.out.print("Enter Company: ");
companyName = kb.nextLine();
System.out.print("Number of hires: ");
noOfHires = kb.nextInt();
kb.nextLine();
//calculations
totalEarnings = noOfHires * 2500 + 10000;
System.out.println("Total Earnings of company is :" + totalEarnings);
totalEarned = "" + totalEarnings;
if(totalEarnings > large ) //If statement for largest number
{
large = totalEarnings;
}
allTotalEarnings += totalEarnings;
count++;
}
You can assign the highest earning company name and its earnings in variables after the calculation by comparing with previous highest with calculated one.
String highCompanyName = "";int highCompanyEarning = 0;
while( count <= noOfComp)
{
System.out.print("Enter Company: ");
companyName = kb.nextLine();
System.out.print("Number of hires: ");
noOfHires = kb.nextInt();
kb.nextLine();
//calculations
totalEarnings = noOfHires * 2500 + 10000;
System.out.println("Total Earnings of company is :" + totalEarnings);
totalEarned = "" + totalEarnings;
if(totalEarnings> highCompanyEarning ) //If statement for largest number
{
highCompanyEarning = totalEarnings;
highCompanyName = companyName;
}
allTotalEarnings += totalEarnings;//the purpose of it is not clear so left as it is.
count++;
}
System.out.println("Highest Earnings company is :" + highCompanyName );
System.out.println("Earning of that company is :" + highCompanyEarning );

Resources