JOptionPane/If statement with increments - if-statement

Okay so I'm still fairly new to this and have a quick question. I have an assignment to write a program that calculates monthly bill. It ask the the customers package type (A, B, or C) and the number of hours that were used. It should display total charges. The kick is that each package has add on prices depending on the hours used.
Example:
Package A is 9.95 and month for 10 hours of access and additional hours are $2.00 and hour. I've got most of it figured out minus how to add the extra charges.
There are also two other packages that will be added. This is just the first bit. =)
This is my first time posting here, I apologize if my formatting sucks
Thanks for the help!
public class InternetServiceProvider {
public static void main(String args []){
double packA = 9.95;
double packB = 13.95;
double packC = 19.95;
String getPackage = JOptionPane.showInputDialog(null, "Please enter your package type:");
String getHours = JOptionPane.showInputDialog(null, "How many hours did you use?");
int hours = Integer.parseInt(getHours);
if (getPackage.equals("a") && hours <=10) {
JOptionPane.showMessageDialog(null, "Your monthly total is: $" + packA );
}
else {
if (getPackage.equals("a") && hours > 10){
JOptionPane.showMessageDialog(null, "Your total is: $" + (hours + 2));
}
}

I don't think this is the place for getting people to do your work for you... Anyway, here is what I would do (I am trying to do it in psuedo code):
package = price
get input for which package the user has
switch (package)
case a:
if hours > 10
hours = hours - 10
final amount = hours * 2 + price of package
else
final amount = price of package
output final amount
case b:
...
case c:
...

Related

How do I make my program stop having build issues and make it stop using negative numbers? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
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.
Closed 2 years ago.
Improve this question
My program needs to be able to calculate the monthly phone bill and there are 3 plans: Basic where 10 hours are free and it costs 9.95, Gold where 20 hours are free and it costs 14.95, and Platinum where you have unlimited hours and it costs 19.95. When my program is given hours less than the free hours it subtracts them from the initial cost, and also it has build hours.
#include <iostream>
#include <string>
using namespace std;
int main()
{
//Set up the variables.
string input;
int hours;
int basicHours;
int goldHours;
float extraBasic;
float basicCost;
float goldCost;
// Will ask and display the user their plan and hours.
cout << "Hello! Welcome to the Comms4You Telecom Company!" << endl;
cout << "Please provide your plan." << endl;
cin >> input;
cout << input << ", Ok now please provide the amount of hours you used." << endl;
cin >> hours;
//Calculate different equations
basicHours = (hours - 10);
goldHours = (20 - hours);
extraBasic = (basicHours * 2);
basicCost = (9.95 + extraBasic);
goldCost = (14.95 + goldHours);
//This part is for displaying to the users plans and hours.(Also calculations)
if (input == "Platinum") {
cout << "Our company thanks you for using " << hours << " hours! " << "Your total cost is $19.95.";
}
else if (input == "Gold") {
cout << "Our company thanks you for using " << hours << " hours! " << "Your total cost is $" << goldCost << ".";
}
else if (input == "Basic") {
cout << "Our company thanks you for using " << hours << " hours! " << "Your total cost is $" << basicCost << ".";
}
else
return 0;
}
The problem is in these lines:
basicHours = (hours - 10);
goldHours = (20 - hours);
extraBasic = (basicHours * 2);
basicCost = (9.95 + extraBasic);
goldCost = (14.95 + goldHours);
Think about what they are doing.
basicHours = (hours - 10);
If hours was 11, then basicHours is now 11 - 10 = 1. This is good. But if hours was 9, then basicHours is now 9 - 10 = -1. This is not what you want; if I used less than my 10 free hours, then you want basicHours to be 0.
So you can write instead:
if (hours > 10) {
basicHours = hours - 10;
}
else {
basicHours = 0;
}
or equivalently:
basicHours = (hours > 10) ? hours - 10 : 0;
goldHours = (20 - hours)
This should be the exact same thing as basicHours, except with 20 instead of 10! I will let you adapt the above code.
basicCost = (9.95 + extraBasic); and goldCost = (14.95 + goldHours);
This is wrong. 9.95 is a monetary value, say in euros. extraBasic is a time, in hours. You cannot add hours with euros! If I used 12 hours with the basic plan, what is the result of 9.95€ + 2h? I do not know, it does not make sense.
If I used 12 hours with the basic plan, then I have to pay 9.95€, and I have to pay for the extra 2h. What is the cost of the extra 2h? It is 2 times the cost of an hour; in other words, it's the extra time multiplied by the hourly rate. You should have a constant variable called hourlyRate or basicHourlyRate in your program, with that value. Then you can write:
basicCost = 9.95 + extraBasic * basicHourlyRate;
goldCost = 14.95 + goldHours * goldHourlyRate;
Coding style: separate data and code
A good rule to follow is never to put data in your code. All literal values are data. The cost of the basic and gold and platinum plans are data. The hourly rate is data. The number of "free" hours for each plan is data. Define a few variables with explicit names, initialize those variables with the data at the very beginning of the code, then write the rest of the code without ever using a literal value. There are two reasons why this is important.
The code will be easier to read with variables. Explicit names in variables make the code meaningful; if you use literal values inside the code, the people reading your code don't know what those values stand for. Why do you subtract 10 from hours? We have to think about where this 10 comes from. However, if you write basicPayingHours = hours - freeBasicHours, we understand immediately. "The people reading your code" include StackOverflow members you're showing your code to, but also your schoolmates or coworkers, your teacher or boss, and most importantly, yourself when you read your code again six months from now.
When the data changes, it will be a lot easier to update your code if data is cleanly separated from code. Imagine you are working for this phone company. Next year, they update their plans and the basic plan is now 9.99 per month instead of 9.95. If this value is stored at the beginning of your code in a line basicPlanInitialCost = 9.95;, it is very easy to update it. However if there are multiple occurrences of 9.95 in your code, you will have to track them and change them all manually - this process is very prone to errors for two reasons: you might accidentally change the cost of something else that also costs 9.95; you might forget to update values that are dependent on the monthly price of the basic cost (like the yearly price of the basic cost, which is 12 * 9.95 = 119.40).

counters updated according to two different conditions within a loop

I am trying to make a call billing program in c++. One of the features of this small program is the ability to update discount minutes spoken within discount hours and normal-priced minutes during business hours, depending on which time stretch is entered.
The user first enters the time as a string like this 22:00
Then I have a function which takes the string and turns it into an integer. For example the 22:00 above is turned into 2200
I have then another help function that takes an int, the int above and turns it to the decimal time.
double turnTimeToDecimal(int timeRaw){
double decimalTime;
decimalTime = timeRaw * 0.01;
return decimalTime;
}
The business hours which bear no discount and are between 8.00 am and 18.30am in order to deal with this feature I update two counters inside a for loop that goes from 0 to 1417minutes (24hrs):
double myStartDecimal = 0.0;
double myStopDecimal = 0.0;
myStartDecimal = turnTimeToDecimal(myStartRaw);
myStopDecimal = turnTimeToDecimal(myStopRaw);
//hours and minutes start
int hourStart = (int)floor(myStartDecimal);
int minuteStart = (int)round(100*(myStartDecimal - hourStart));
//hours and minutes stop
int hourStop = (int)floor(myStopDecimal);
int minuteStop = (int) round(100*(myStopDecimal - hourStop));
int totalMinutesPremium = 0;
int totalMinutesDiscount = 0;
int i = 0;
int k = 0;
for(k = (hourStart* 60) + minuteStart; k < (hourStop * 60) + minuteStop + round(((double)minuteStop/100)); k++){
//will update the corresponding counter depending
//on the time stretch, business hours 8.00 - 18.30.
if(hourStart >= 8 && hourStop < 18.5){
totalMinutesPremium++;
}else{
totalMinutesDiscount++;
}
}
//will give total minutes
cout << " k is: " << k << endl;
//will give the total number of minutes during the business hours and
//the total number of minutes during the discount hours(non-bussiness hours)
cout << "Total minutes premium " << round(totalMinutesPremium) <<
" Total Minutes discount " << round(totalMinutesDiscount) << endl;
However, the program does detects whether the time stretch entered is within business hours or not, except in one case. If the time for example lies between 7:30 and 8:30 (business hours between 7:59-18:30) it does not return the combination of minutes within the business hours which I would expect to be 30 min and minutes within the discount hours which I would expect to be 30 minutes as well, since the discount stretch ends at 07:59 and it starts again at 18:31.
Hopefully I made myself clear.
Inside the for loop, you allocate the given minute depending on hourStart and hourStop, not on whether the given minute is during business hours. If the call encroaches on discount hours, then the whole call will be discounted.
"However HourStop is an int. same thing goes for hourStart"
Then it's not going to work, if can't use decimal values with ints like you do here:
hourStop < 18.5
well.. you can but it's not going to work the way you want it to. If you have int hourStop = 18.5 then it's going to get truncated to 18 since it can't be a fractional number. You need to use a different type, such as double
Also, the condition in your loop depends on hourStart and hourStop which are never changing in the loop:
if(hourStart >= 8 && hourStop < 18.5){
So you'll always hit the same if condition (which ever it is)
Why use a loop? Why not just do the math?
While not the complete code answer... you can fill in the blanks...
if( startTime >= startOfPremiumPeriod && endTime <= endOfPremiumPeriod )
totalMinutesPremimum = endTime - startTime;
else if( startTime < startOfPremiumPeriod && endTime < startOfPremimumPeriod )
totalMinutesDiscount = endTime - startTime;
.... etc. etc. etc.
You can take into account the case where the start time is before midnight and the end time after midnight by adding 24 hours to the end time...
if( endTime < startTime ) endTime += 1440;

am i on the right track? Cashier Program C++

I'm new to C++ and was wondering if i was on the right track? I'm kind of confused about this but was hoping for possibly some helpful hints on things i am missing/ have wrong....i know its not completely finished i still need to do the breakdown of the dollars,quarters....etc
Question: A cash register uses an automated coin machine to help make change. We assume that a clerk is handed money to pay for purchases. For change, the clerk returns to the customer any paper money and directs the coin machine to distribute any changes less then $1. In this exercise, you are to simulate the action of the clerk and the machine.
At the cash register, we need access to the purchase price and the payment. The change, which is the difference between the payment and the purchase prices, is a real number. The whole part represents the change in dollars and the fractional part is the change in cents that is returned in quarters, dimes, nickels, and pennies. For instance, with a payment of $10 to cover purchases of $3.08, the required change is $6.92. The clerk hand out $6 and the coin machine distributes 3 quarters, 1 dime, 1 nickel, and 2 pennies for the 92 cents.
92 = 3(25) + 1(10) + 1(5) + 2
Use real-number objects that identify the purchase price (price), the amount of payment (payment), and the change (change). The main program computes the amount of change (coinChange) and partitions it into dollars (dollars), quarters (quarters), dimes (dimes), nickels (nickels), and pennies (pennies).
You must declare constants for quarters (quarters), dimes (dimes), nickels (nickels), and pennies (pennies). You must use compound operators in the calculations. You must use setreal(w,p) and setw(n) for the output.
What I have done so far:
// Me
// A BRIEF PROGRAM DESCRIPTION FOR CHAPTER 2, HOMEWORK 4
// COMMENT THE PREPROCESSOR
#include <iostream.h>
// COMMENT THE PREPROCESSOR STATEMENT
#include "textlib.h"
int main( )
{
// COMMENT THE CONSTANTS
const int QUARTER_AMOUNT = 25;
const int DIME_AMOUNT = 10;
// COMMENT THE OBJECTS
double price;
double payment;
double change;
int numofDollars;
int numofQuarters;
int numofDimes;
int numofNickles;
int numofPennies;
int coinChange;
cout << "Enter the purchase total: ";
cin >> price;
cout << "Enter the payment: $";
cin >> payment;
// COMMENT THE CALCULATION
change = payment - price;
numofDollars = int(change);
coinChange = (int((change / numofDollars) * 100));
numofQuarters = coinChange / 25;
coinChange = coinChange / (numofQuarters * 25);
numofDimes = coinChange / 10;
numofNickles = coinChange / 5;
numofPennies = coinChange / 1;
// OUTPUT THE INFORMATION
return 0;
}
Yes, you are on the right track. Your general structure is sound. These sorts of homework assignments almost always have a structure like this:
int main () {
// read in the data
...
// Do the math
...
// Write out the data
...
}
You do have some math errors. Try stepping through the code with a pencil and paper, pretending that you are the computer. Also, try stepping through the code with your debugger, examining the variables after each line. Compare what actually happened to what you expected.

How do I use getline and stringstream to parse formatted date and time input?

I have only been working on c++ for about a month. I am not really understanding how it works, however I need to write a program for school. I used a void function and it seems to be working so far,but I have no idea what to do next I am lost at line 44, I am not sure how to make it work, is there a way to take a value from a certain string? If the value is in both strings how would I determine which value? Here is my assignment:
A parking garage charges a $2.00 minimum fee to park for up to three hours. The garage charges an additional $0.50 per hour for each hour or part thereof in excess of three hours. The maximum charge for any given 24-hour period is $10.00. People who park their cars for longer than 24 hours will pay $8.00 per day.
Write a program that calculates and prints the parking charges. The inputs to your program are the date and time when a car enters the parking garage, and the date and time when the same car leaves the parking garage. Both inputs are in the format of YY/MM/DD hh:mm
Here's the code I've written so far:
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <cmath>
#include <algorithm>
#include <sstream>
using namespace std;
stringstream ss;
string enter_date;
string enter_time;
string exit_date;
string exit_time;
int calculatecharge;
int num;
int i;
int year;
int month;
int ddmmyyChar;
int dayStr;
string line;
int x;
void atk()
{
getline (cin,line); // This is the line entered by the user
stringstream ss1(line); // Use stringstream to interpret that line
ss >> enter_date >> enter_time;
stringstream ss2(enter_date); // Use stringstream to interpret date
string year, month, day;
getline (ss2, year, '/');
}
int main()
{
cout << "Please enter the date and time the car is entering "<< endl
<< "the parking garage in the following format: YY/MM/DD hh:mm"<< endl;
atk();
cout << "Please enter the date and time the car is exiting "<< endl
<< "the parking garage in the following format: YY/MM/DD hh:mm"<< endl;
atk();
if (hr - hr < 3)
cout<<"Parking fee due: $2.00" << endl;
Write a program that calculates and prints the parking charges.
This is the goal of our program. Basically, this is the output.
The inputs to your program are the date and time when a car enters the
parking garage, and the date and time when the same car leaves the
parking garage. Both inputs are in the format of YY/MM/DD hh:mm
So, we want some way of translating the date format entered as a string into a time difference. You could store the time in an int, which represents the amount of minutes elapsed during the parking period (I choose minutes since this is the smallest time period inputted). The challenge here is the parsing of the string into this integer.
You could write a function like this:
int parseDate( std::string dateStr )
{
// Format: YY/MM/DD hh:mm
int year = atoi( dateStr.substr( 0, 2 ).c_str() );
int month = atoi( dateStr.substr( 3, 2 ).c_str() );
int day = atoi( dateStr.substr( 6, 2 ).c_str() );
int hour = atoi( dateStr.substr( 9, 2 ).c_str() );
int min = atoi( dateStr.substr( 12, 2 ).c_str() );
// Now calculate no. of mins and return this
int totalMins = 0;
totalMins += ( year * 365 * 24 * 60 ); // Warning: may not be accurate enough
totalMins += ( month * 30 * 24 * 60 ); // in terms of leap years and the fact
totalMins += ( day * 24 * 60 ); // that some months have 31 days
totalMins += ( hour * 60 );
totalMins += ( min );
return totalMins;
}
Careful! My function here is just an illustration, and does not take into account subtleties like leap years and varying month length. You will probably need to improve on it. The important thing is to recognise that it attempts to take a string and return the number of minutes that have elapsed since year '00. This means we simply have to subtract two integers from the two date strings to find the elapsed time:
int startTime = parseDate( startDateString );
int endTime = parseDate( endDateString );
int elapsedTime = endTime - startTime; // elapsedTime is no. of minutes parked
This is probably the hardest part of the problem, once you have this worked out, the rest should be more straightforward. I will give you a few more tips:
A parking garage charges a $2.00 minimum fee to park for up to three
hours.
Basically just a flat rate: No matter what, the output variable that describes the cost should be equal to at least 2.00.
The garage charges an additional $0.50 per hour for each hour
or part thereof in excess of three hours.
Work out the amount of hours elapsed past three hours - subtract 180 from elapsedTime. If this is greater than 0, then divide it by 60 and store the result in a float (since it is not necessarily an integer result), called, say, excessHours. Use excessHours = floor( excessHours ) + 1; to round this number up. Now multiply this by 0.5; this is the extra cost. (Try to understand why this works mathematically).
The maximum charge for any
given 24-hour period is $10.00. People who park their cars for longer
than 24 hours will pay $8.00 per day.
I will leave this up to you to work out, since this is homework after all. Hopefully I have provided enough here for you to get the gist of what needs to be done. There are many possible approaches to this problem too, this is just one, and may or may not be "the best".
First of all as both the string for the date and the string for the time are continuous(contain no spaces), you do not need to use stringstream to parse the line. You can read the date and time just like this:
cin >> enter_date >> enter_time;
cin >> exit_date >> exit_time;
Now what you need is to convert these strings to actual dates and times. As the format of both is fixed you can write something like this:
void parse_date(const string& date_string, int& y, int& m, int& d) {
y = (date_string[0] - '0')*10 + date_string[1] - '0'; // YY/../..
m = (date_string[3] - '0')*10 + date_string[4] - '0'; // ../mm/..
d = (date_string[6] - '0')*10 + date_string[7] - '0'; // ../../dd
}
Of course this code is somewhat ugly and can be written in better way but I believe this way it is easier to understand. Having this function it should be obvious how to write this one:
void parse_time(const string& time_string, int& h, int &m);
Now that you have the date and time parsed, you need to implement a method that subtracts two dates. IN fact what you care about is the number of hours that elapsed from the enter date time to the exit date time rounded up. What I suggest here is that you convert the dates to number of days from some initial moment(say 00/01/01) and then subtract the two values. Then convert both times to number of minutes since 00:00 and again subtract them. This is not language specific so I believe these tips should be enough. Again using some built-in libraries this can be done easier but I don't think this is the idea of your assignment.
After you have the number of hours rounded up all you need to do is actually to implement the rules in the statement. This will only take a few ifs and is in fact quite easy.
Hope this helps. I am purposefully not giving more detailed explanations so that there is something left for you to think about. After all this is homework and is meant to make you think how to do it.
You don't need to perform separate input reading and parsing operations. You could pass the necessary variables by reference and read the input directly into the variables using stringstream. I would use a structure to store the date and time and overload operator- with an algorithm for subtracting two date/time values. Here's how I would do it:
#include <iostream>
#include <sstream>
using namespace std;
struct DateTime {
// Variables for each part of the date and time
int year, month, day, hour, minute;
// Naive date and time subtraction algorithm
int operator-(const DateTime& rval) const {
// Total minutes for left side of operator
int lvalMinutes = 525600 * year
+ 43200 * month
+ 1440 * day
+ 60 * hour
+ minute;
// Total minutes for right side of operator
int rvalMinutes = 525600 * rval.year
+ 43200 * rval.month
+ 1440 * rval.day
+ 60 * rval.hour
+ rval.minute;
// Subtract the total minutes to determine the difference between
// the two DateTime's and return the result.
return lvalMinutes - rvalMinutes;
}
};
bool inputDateTime(DateTime& dt) {
// A string used to store user input.
string line;
// A dummy variable for handling separator characters like "/" and ":".
char dummy;
// Read the user's input.
getline(cin, line);
stringstream lineStream(line);
// Parse the input and store each value into the correct variables.
lineStream >> dt.year >> dummy >> dt.month >> dummy >> dt.day >> dummy
>> dt.hour >> dummy >> dt.minute;
// If input was invalid, print an error and return false to signal failure
// to the caller. Otherwise, return true to indicate success.
if(!lineStream) {
cerr << "You entered an invalid date/time value." << endl;
return false;
} else
return true;
}
From here, in the main() function, declare two DateTime structures, one for the entry time and one for the exit time. Then read in both DateTime's, subtract the entry time from the exit time, and use the result to generate the correct output.

C++ reverse number with digit adding

Hi to all thank all in advance to those who tried to answer or answer and part of this question.
Calculate the sum of the digits of the year.
Calculate the absolute value of the difference between the year and the ’reverse’ of the year.
Calculate the number of even factors of the day.
Calculate the greatest common divisor of the day, month and year.
Calculate the number of steps required to solve the Collatz problem for
the month
These are my tasks that I need to fulfill, as Engineering student this how far I went in this. In the following codes I expect something like this
19
90
0
1
0
T M B B
The answer that I get is
Please enter your birthdate (dd mm yyyy): 12 11 1981
19
8468304
Press any key to continue . . .
8468304
How to get it right I know that my equation is right or(formula, method). However this is what I know.
#include<iostream>
#include<cstdlib>
using namespace std;
int main()
{
cout << "Please enter your birthdate (dd mm yyyy): ";
int day, month, year, count,rev;
int sum = 0;
cin >> day>> month >>year;
while (year!=0)
{
int count = year%10;
sum +=count;
year /= 10;
}
while(year>0)
{
rev = year%10;
year=year/10;
}
cout<<sum<<endl;
cout << rev;
system ("pause");
return 0;
}//end main
Please help!
After your first loop, while (year != 0), you don't reset the value of year, so it remains at zero and the second loop doesn't execute at all.
You need to save the value of year and use it when you start the second loop.
Just a note on organisation: I'd suggest to write a subroutine/function for every task, like
int digit_sum(int year) {
/* ... */
return sum;
}
int reverse_difference(int year) {
/* ... */
return diff;
}
and so on. This way you'll also prevent errors like modifying the year variable during the first calculation without saving the original value (which you did, as David Winant already pointed out).