Java Calculating salary - java

I am clocking start and stop for workingtime, hh:mm.
Salary is 150 / hour.
I get the indata:
hour1 = keyboard.nextInt();
minute1 = keyboard.nextInt();
keyboard.nextLine();
hour2 = keyboard.nextInt();
minute2 = keyboard.nextInt();
Total hours:
totHours = hour2 - hour1;
Total minutes:
totMinutes = (minute2 + minute1)/60;
totTime = totHours + totMinutes;
totSalary = totTime*Salary;
It doesnt work. The result just counts the differens between hour2 and hour1 and ignores the minutes.

It seems like your hours and minutes are of type int; at least you are using nextInt to get the values, and I can reproduce your problem that way.
int hour1 = 12;
int minute1 = 45;
int hour2 = 14;
int minute2 = 30;
double totHours = hour2 - hour1;
double totMinutes = (minute2 + minute1)/60; // 1.0
double totTime = totHours + totMinutes; // 3.0
This is because if both the dividend and the divisor are integers, then / will also produce an integer, i.e. the floor of the actual division. Divide by 60.0, then it works. Also, use -, not +. And of course make sure to store the result in a double.
double totMinutes = (minute2 - minute1)/60.0; // -0.25
double totTime = totHours + totMinutes; // 1.75
However, as pointed out in comments, it might be wiser to use a library for date/time calculations.

Related

Java - Least number of bills and coins for change

I have to do an assignment for my class that allows the user to key in two amounts - the first should be the total sale amount and the next would be the amount of change handed to the cashier. The program needs to calculate the change needed and tell the cashier how many of each monetary amount to return to the customer using the least number of bills and coins. Using $20, 10, 5, 1 and 0.25, 0.10, 0.05, and 0.01. I also need to include a while loop to make sure the cashier is given an amount greater than the amount due.
I have the following so far, but don't know where to go from here:
public class Change {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//Enter sale amount less than $100
System.out.println("Enter the sale amount: ");
double price = input.nextDouble();
//Enter amount of money handed to cashier less than $100
System.out.println("Enter the amount of money handed to the cashier: ");
double payment = input.nextDouble();
double difference = payment - price;
int num20 = (int)(difference / 20);
System.out.println("num20 = " + num20);
difference = difference % 20;
System.out.println("difference = " + difference);
int num10 = (int)(difference / 10);
System.out.println("num20 = " + num10);
difference = difference % 10;
System.out.println("difference = " + difference);
int numQtr = (int)(difference / .25);
System.out.println("numqtr = " + numQtr);
int numDime = (int)(difference / .10);
System.out.println("numDime = " + numDime);
}
Use the mod operator and division to find values at each step
29 % 20 -> 9
(int) (29 / 20) -> 1
9 % 10 -> 9
(int) (9 / 10) -> 0
please note that casting the result of a division to an integer will truncate the returned value to a whole number.

Troubles with a math formula - Java

I'm making a program for my java class that calculates the population for a year given the start year (2011) and increases the population by 1.2% every year. The population for 2011 is 7.000 (I'm using decimals, instead of billions). I currently have this code.
int startYear = 2011;
int endYear = user_input.nextInt();
double t = 1.2; //Population percent increase anually
double nbr = (endYear - startYear); //Number of years increased
double pStart = 7.000; //Starting population of 2011
double pEnd = pStart * Math.exp(nbr * t); // Ending population of user input
DecimalFormat nf = new DecimalFormat("2");
System.out.println("Population in " + endYear + ": " (nf.format(pEnd)));
There's no errors in the code, everything works, but I'm having troubles with the pEnd equation. Currently when I enter 2016 for the end year, i get 22824. I've tried googling a formula, but i can't find anything. Do any of you guys have an idea of the formula? If you enter 2016 for the end year, it should be around 7.433
You're incrementing by a factor of 1.2, which would represent 120% instead of 1.2%. I think what you want is :
double t = 0.012;
This change gives me an exact value of 7.4328558258175175 from 2011 to 2016.
EDIT : here's the code as requested by the author :
public static void main(String args[]){
int startYear = 2011;
int endYear = 2016;
double t = 0.012; //Population percent increase anually
double nbr = (endYear - startYear); //Number of years increased
double pStart = 7.000; //Starting population of 2011
double pEnd = pStart * Math.exp(nbr * t); // Ending population of user input
System.out.println("Population in " + endYear + ": " + pEnd);
}
Use Math.pow(1 + t / 100, nbr) instead of Math.exp(nbr * t) because you need (1+t/100)^nbr (i.e. multiply 1 + t / 100 on itself nbr times), not exp^(nbr*t):
double pEnd = pStart * Math.pow(1 + t / 100, nbr); // Ending population of user input
Try this.
double pEnd = pStart * Math.pow(1.0 + t / 100, nbr);

Program will not do calculations

int single = 0, doub=0, triple=0, homer=0, atbats=0, totalbase, totalhits;
double slug, battingavg;
Scanner sc = new Scanner(System.in);
System.out.print("Enter singles (-1 to end): ");
single = sc.nextInt();
while (single != -1)
{
System.out.print("Enter doubles: ");
doub = sc.nextInt();
System.out.print("Enter triples: ");
triple = sc.nextInt();
System.out.print("Enter home runs: ");
homer = sc.nextInt();
System.out.print("Enter total at bats: ");
atbats = sc.nextInt();
System.out.print("Enter the player's name: ");
String name = sc.next();
totalbase = (single + doub * 2 + triple * 3 + homer * 4);
slug = totalbase / atbats;
battingavg = (single + doub + triple + homer) / atbats;
System.out.println("Player's name is " + name);
System.out.printf("The slugging percentage is %.3f\n", + slug);
System.out.printf("The batting percentage is %.3f\n", + battingavg);
System.out.print("Enter singles (-1 to end): ");
single = sc.nextInt();
}
This program will only output a 1 or a 0 after the calculations. Everything else works fine, but It just doesn't seem to do the calculations.
The problem is that when you do integer divisions, you'll get integer values. Instead use double or float data types. I see slug and battingavg are already doubles, but you're assigning the result of an integer division to them. If you cast at least one of the values in your calculations to a double you should get the output you expect. Example:
slug = totalbase / (double) atbats;
battingavg = (single + doub + triple + homer) / (double) atbats;
When you divide integer values and store the result in a double that is a widening conversion, but the value was calculate as an integer and thus you're widening the integer value.
Change this,
slug = totalbase / atbats;
battingavg = (single + doub + triple + homer) / atbats;
to something like this,
slug = ((double) totalbase / atbats);
battingavg = ((double) (single + doub + triple + homer) / atbats);
to get double values into your double variables.

Formatting a double to minutes and seconds

I'm trying to let the user enter the length of a song except they can enter the length as 5.76 for example. Is there a way I can format that 6.16?
This is how they enter the duration if it makes any difference:
System.out.println("Please enter the length of the song");
double length = sc.nextDouble();
The code below will split the entered time into minutes and seconds, and then operate on the seconds entry to calculate the total number of minutes and seconds are represented by that number.
EDIT Modified the code so that trailing zeroes are not truncated.
System.out.println("Please enter the length of the song");
String length = sc.next("\\d+\\.\\d{2,}");
String[] split = ("" + length).split("\\.");
double minutes = Double.parseDouble(split[0]);
double seconds = (Double.parseDouble(split[1]));
seconds = (Math.floor(seconds / 60)) + ((seconds % 60) / 100);
System.out.println(minutes + seconds);
Get the decimal value and check if its greater than 0.6. You can then subtract it from 0.6 and add that difference and 1 to the floor of the orignal number.
double dec = length - Math.floor(length);
if(dec > 0.6){
double diff = dec - 0.6;
length = length + 1 - dec + diff;
}
However, this might cause a lot of decimals due to the way double is stored in Java. You could get around this, but you should really use a different value to store hours and minutes than a double. You could use an integer for each, and you could initially scan in the input as a String and then process it.
With the following code, you can convert to minutes and seconds, then output that however you want, including put it back into a double (as shown).
int minutes = Math.floor(length);
length -= minutes;
length = Math.floor(length * 100.0);
if (length > 59) {
minutes++;
length -= 60;
}
int seconds = Math.floor(length);
length = ((double) minutes) + ((double) seconds) / 100.0;

Change Machine Math & Logic Errors

I've posted this program once before but realized I was overthinking it by adding loops and what not. I've paired it down a bit but still running into problems. The program is supposed to be a change machine. After the user inputs price, the program should round it up to the nearest dollar then output how much change will be dispensed and a count of which coins. The output is completely wrong at this point. I'm very new to programming and I'm at a loss.
package changemachine;
import java.util.Scanner;
import java.text.*;
public class Main
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter Purchase Price: ");
double price = scan.nextDouble();
int newPrice = (int)(price*100);
int paid = (int)(newPrice+1);
int change = (int)(paid - newPrice);
int quarters = (int)(change/25);
int dimes = (int)((change%25)/10);
int nickels = (int)((change%25%10)/5);
int pennies = (int) (change%25%10%5);
System.out.println("Dispensing: " + quarters + " Quarters,"
+ dimes + "Dimes," + nickels + "Nickels,"
+ pennies + "Pennies.");
System.out.println("Program written by Ashley ");
}
}
(Once newPrice is an int, you can stop casting every line.) Instead of chaining % together, it would be more readable (and less error prone) to subtract off the values you've found:
change -= 25*quarters;
dimes = change / 10;
change -= 10*dimes;
nickels = change / 5;
change -= 5*nickels;
pennies = change;
I think it would help you to understand if you would go through the code by hand and think about what price, newprice, paid, and change are.
newprice is the price round down to the lower dollar.
paid is the cost of the item.
change is the amount you paid minus the cost converted into an integer number of pennies.
package changemachine;
import java.util.Scanner;
import java.text.*;
public class Main
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter Purchase Price: ");
double price = scan.nextDouble();
int newPrice = (int)(price);
int paid = (int)(newPrice+1);
int change = (int)((paid - price) * 100);
int quarters = (int)(change/25);
int dimes = (int)((change%25)/10);
int nickels = (int)((change%25%10)/5);
int pennies = (int) (change%25%10%5);
System.out.println("Dispensing: " + quarters + " Quarters,"
+ dimes + "Dimes," + nickels + "Nickels,"
+ pennies + "Pennies.");
System.out.println("Program written by Ashley ");
}
}
If instruction int paid= (int)(newPrice+1) ; is supposed to be rounding to next dollar, then it should be: int paid= ( newPrice + 99 ) / 100 * 100 ; You don't need to convert to (int) when both operands are already ints. Makes your program slightly illegible. Later, after obtaining the number of quarters by quarters= change / 25 ;(that's correct in your program), you can reduce the amount fromchangewithchange-= quarters * 25 ;`.
This makes calculating dimes exactly the same as quarters, just that using 10 instead of 25. Don't forget reducing the dimes from the pending change again with change-= dimes * 10 ;. You can repeat the process with nickels and the remaining change will be pennies.
If you have any doubt, use a debugger or output each intermediate result with System.out. You can always delete them later once you understand your program's behavior.
This is how I made Java choose what coins I must pay with.
int temp = m;
int quarterCoin = 25;
int x = m/quarterCoin;
m=m-x*quarterCoin;
int dimeCoin = 10;
int z = m/dimeCoin;
m=m-z*dimeCoin;
int nickelCoin = 5;
int y = m/nickelCoin;
m=m-y*nickelCoin;
int pennyCoin = 1;
int w = m/pennyCoin;
m=m-w*pennyCoin;
Instead of giving you the answer/solution to your homework, I am going to help you figure out how to figure it out. :)
In order to adequately debug your software and troubleshoot what's going on, you need to know what your variables are doing. There are two methods:
Attach a debugger - Most IDEs will come with a debugger that will help you accomplish this.
Print out your variables to the console. This is my preferred method. Me and debuggers never have gotten along well together. :)
So, here is what I would do if I were trying to figure your program out:
import java.util.Scanner;
public class Change {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
// System.out.println("Enter Purchase Price: ");
double price = 5.65d;//scan.nextDouble();
int newPrice = (int) (price * 100);
System.out.println("newPrice: " + newPrice);
int paid = (int) (newPrice + 1);
System.out.println("paid: " + paid);
int change = (int) (paid - newPrice);
System.out.println("change: " + change);
int quarters = (int) (change / 25);
int dimes = (int) ((change % 25) / 10);
int nickels = (int) ((change % 25 % 10) / 5);
int pennies = (int) (change % 25 % 10 % 5);
System.out.println("Dispensing: " + quarters + " Quarters,"
+ dimes + "Dimes," + nickels + "Nickels,"
+ pennies + "Pennies.");
System.out.println("Program written by Ashley ");
}
}
(Note: Instead of utilizing the scanner, I just manually entered "5.65" into the price variable just to save time)
Which produces the output:
newPrice: 565
paid: 566
change: 1
Dispensing: 0 Quarters,0Dimes,0Nickels,1Pennies.
Program written by Ashley
So, now you can see what your program is doing wrong. Can you spot it?

Categories

Resources