sorry guys this is my first week at programming and my task is to design a program that calculates regular pay and overtime pay based on user input, but when I put 5.5 in hours or rates it gives me errors I don't really understand why
if there is way to fix the error then how do you get rid of .0 at the end of output integers? thanks a bunch, teacher just assumed we know all the stuff when I took AP CS, this is the review from last years "intro class" so I'm bit overwhelmed, if still have some time left, can you please explain the mechanism behind "double"? to my understanding so far it means you can use decimals as opposed to int where you can only put integers code here
`
import javax.swing.JOptionPane;
public class Salary
{
public static void main(String[] args)
{
String s1, s2;
double number1, number2;
s1=JOptionPane.showInputDialog("Enter the number of hours worked");
s2=JOptionPane.showInputDialog("Enter the rates per hour");
number1 = Integer.parseInt ( s1);
number2 = Integer.parseInt ( s2);
double elseregularp = ( 40*number2);
double regularp = ( number1*number2);
double othours = (number1-40);
double othourspay = ( number2* 15/10.0);
if( number1 <= 40)
{
System.out.println("YOU WORKED "+number1+" HOURS" );
System.out.println("YOU EARNED $"+number1 * number2+" REGULAR PAY");
}
else
{
System.out.println("YOU WORKED " + number1+" HOURS");
System.out.println("YOU EARNED $"+elseregularp+" REGULAR PAY");
System.out.println("AND $" +(othours)*(othourspay)+ " IN OVERTIME");
System.out.println("YOUR TOTAL CHECK IS $" + ((elseregularp)+(othours)*(othourspay)));
}
}
}
`
integer.parseInt(...) is accepting a string value which is not the correct input for it. So change it to parseDouble so that it works correctly.
Your final code after modification.
integer.parseInt (...) is changed to Double.parseDouble(...)
import javax.swing.JOptionPane;
public class Salary
{
public static void main(String[] args)
{
String s1, s2;
double number1, number2;
s1=JOptionPane.showInputDialog("Enter the number of hours worked");
s2=JOptionPane.showInputDialog("Enter the rates per hour");
// number1 = Integer.parseInt ( s1);
// number2 = Integer.parseInt ( s2);
number1=Double.parseDouble(s1);
number2=Double.parseDouble(s2);
double elseregularp = ( 40*number2);
double regularp = ( number1*number2);
double othours = (number1-40);
double othourspay = ( number2* 15/10.0);
if( number1 <= 40)
{
System.out.println("YOU WORKED "+number1+" HOURS" );
System.out.println("YOU EARNED $"+number1 * number2+" REGULAR PAY");
}
else
{
System.out.println("YOU WORKED " + number1+" HOURS");
System.out.println("YOU EARNED $"+elseregularp+" REGULAR PAY");
System.out.println("AND $" +(othours)*(othourspay)+ " IN OVERTIME");
System.out.println("YOUR TOTAL CHECK IS $" + ((elseregularp)+(othours)*(othourspay)));
}
}
}
Related
I am trying to accept user input for two people's hourly wage and the amount of hours of overtime they work per year.
using an algorithm I have researched, the program will tell both people the amount of money they make per year and the amount of taxes they pay, which is based on the amount that they make.
This is all fine and dandy. However, what I am now trying to do is to add a line at the end of the program which states who is paying more taxes. This would be accomplished with the method whoPaysMoreTaxes, but I have no idea what to include in that method. I know I would need a simple if/ else if/ else statement to get the job done, but I do not know how I would go about storing the taxes of person 1 and the taxes of person 2 and compare them. The output should be as follows I believe. The numbers 22, 100, 58, and 260 are user input:
Person 1's hourly wage: 22
Person 1's overtime hours for the year: 100
You will make $45540 this year
And you will pay $9108 in taxes
Person 2's hourly wage: 58
Person 2's overtime hours for the year: 260
You will make $133980 this year
And you will pay $40194 in taxes.
Person 2 is paying more taxes.
The issue I am having is finding a way to produce that final line that says who is paying more taxes.
public class conditionalsAndReturn
{
public static void main(String[] args)
{
Scanner console = new Scanner(System.in);
taxes(console, 1);
taxes(console, 2);
}
public static void taxes(Scanner console, int personNum)
{
System.out.print("Person " + personNum + "'s hourly wage: ");
int wage = console.nextInt();
System.out.print("Person " + personNum + "'s overtime hours for the year: ");
double totalOvertimeHours = console.nextInt();
int salary = annualSalary(wage, totalOvertimeHours);
System.out.println("You will make $" + salary + " this year");
System.out.println("And you will pay $" + taxation(salary) + " in taxes");
System.out.println();
}
public static int annualSalary(int wage, double totalOvertimeHours)
{
double workHoursPerWeek = 40 + totalOvertimeHours / 48;
return (int)(weeklyPay(wage, workHoursPerWeek) * 48);
}
public static double weeklyPay(int wage, double workHoursPerWeek)
{
if (workHoursPerWeek > 40)
{
return (wage * 40) + ((wage + wage / 2.0) * (workHoursPerWeek - 40));
}
else
{
return wage * workHoursPerWeek;
}
}
public static int taxation(int salary)
{
if (salary < 20000)
{
return 0;
}
else if (salary > 100000)
{
return salary * 3 / 10;
}
else
{
return salary * 2 / 10;
}
}
public static String whoPaysMoreTaxes(
}
The OOP conform coding would be, to have a class person (or better employee), with the fields: personNum, one or more of the three wage/salary variables, taxation. Add name and such if needed.
Now you can use instances of those class to store the accumulated data, and compare the objects with a compareTo.
If you were to follow true Object Oriented programming principles, then you might create a separate class which represents a Person object (or consider a nested class). Then each Person instance could have the attributes:
hourly_wage
overtime_hours
income
taxes_owed
You would then want to create as many People classes as you need, using the class instances to store data. You could then modify your method header to be:
public Person who_payes_more_taxes(Person p1, Person p2): { ... }
Inside the method you would need to decide how to compare taxes, but most likely it will look something like:
if (p1.taxes_owed > p2.taxes_owed) { return p1 }
You're definitely on the right track. I would use more variables to simplify comparing the taxes:
import java.util.Scanner;
public class ConditionalsAndReturn
{
public static void main(String[] args)
{
int personOneWage;
int personOneOvertime;
double personOnePayBeforeTax;
double personOneTaxes;
double personOneNetIncome;
int personTwoWage;
int personTwoOvertime;
double personTwoPayBeforeTax;
double personTwoTaxes;
double personTwoNetIncome;
Scanner scan = new Scanner(System.in);
System.out.print("Person 1's hourly wage: ");
personOneWage = scan.nextInt();
System.out.print("Person 1's overtime hours for the year: ");
personOneOvertime = scan.nextInt();
personOnePayBeforeTax = (40 * personOneWage) + (personOneOvertime * personOneWage * 1.5);
personOneTaxes = taxes(personOnePayBeforeTax);
personOneNetIncome = personOnePayBeforeTax - personOneTaxes;
System.out.println("You will make $" + personOneNetIncome + " this year");
System.out.println("And you will pay $" + personOneTaxes + " in taxes");
System.out.print("Person 2's hourly wage: ");
personTwoWage = scan.nextInt();
System.out.print("Person 2's overtime hours for the year: ");
personTwoOvertime = scan.nextInt();
personTwoPayBeforeTax = (40 * personTwoWage) + (personTwoOvertime * personTwoWage * 1.5);
personTwoTaxes = taxes(personTwoPayBeforeTax);
personTwoNetIncome = personTwoPayBeforeTax - personTwoTaxes;
System.out.println("You will make $" + personTwoNetIncome + " this year");
System.out.println("And you will pay $" + personTwoTaxes + " in taxes");
if (personOneTaxes > personTwoTaxes)
{
System.out.println("Person 1 is paying more in taxes.");
}
else
{
System.out.println("Person 2 is paying more in taxes.");
}
scan.close();
}
private static double taxes(double payBeforeTax)
{
if (payBeforeTax < 20000)
{
return 0;
}
else if (payBeforeTax > 100000)
{
return payBeforeTax * 3 / 10;
}
else
{
return payBeforeTax * 2 / 10;
}
}
}
I have the program working I just need help cutting off the extra numbers, Im not very skilled at using the printf statements when printing in Java. When I run it I get output like 1225.043 Here is what I have:
import java.util.Scanner;
public class Comparison {
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
float amount;
double principal = 1000.00;
double rate;
System.out.println("Enter interest rate");
rate = keyboard.nextDouble();
System.out.println("Year" +" "+ "Amount on deposit");
for(int year = 1; year <= 10; ++year)
{
amount = (float) (principal * Math.pow(1.0 + rate, year));
System.out.println(year+ " "+ amount);
System.out.println();
}
}
}
Try
System.out.printf("%2d %.2f%n", year, amount);
Output:
Enter interest rate
0.1
Year Amount on deposit
1 1100.00
2 1210.00
3 1331.00
4 1464.10
5 1610.51
6 1771.56
7 1948.72
8 2143.59
9 2357.95
10 2593.74
I hope I'm posting in the right place.
I'm pretty new to Java (meaning this is only my third program besides 'hello world').
I have a tip calculator I'm working on for an assignment. I'm not getting an 'error' as such,
but the method for splitting the bill always seems to think each customer pays 'infinity'.
I have my program set up in two classes: tipCalc1 and tipCalc2 (no points for originality of course).
The program appears to run without issue besides the 'infinity' issue.
Here's what I have so far. Any assistance appreciated, thanks.
***TipCalc1 Class:***
import java.util.Scanner;
public class Tipcalc1
{
public static void main(String[] args)
{
System.out.println("Welcome to Tip Calculator! ");
TipCalc2 Calculator = new TipCalc2();
System.out.println("Please enter the bill amount: ");
TipCalc2.calBill();
System.out.println("What percentage would you like to tip?: ");
Calculator.percTip();
}
}
***And the tipCalc2 class which does the dirty work:***
import java.util.Scanner;
public class TipCalc2
{
static double bill;
double tip;
double total;
double split;
double splitPrompt;
double Y;
double N;
double billPerPerson;
static Scanner scan = new Scanner(System.in);
public static void calBill()
{
bill = scan.nextDouble();
}
public void percTip()
{
tip = scan.nextDouble();
if(tip<1)
{
total = bill * tip;
}
else total = bill * (tip/100);
System.out.println("Your total is: " + total);
Split();
}
public void Split()
{
System.out.println("Would you like to split the bill? ");
System.out.println("Enter 1 for YES or 0 for NO: ");
splitPrompt = scan.nextDouble();
if(splitPrompt == 0)
{
System.out.println("Your total is: " + total);
System.out.println("Thankyou. Goodbye.");
System.out.println("End Program");
}
if(splitPrompt == 1)
{
System.out.println("How many ways would you like to split the bill? ");
splitPrompt = scan.nextDouble();
billPerPerson = total / split;
System.out.println("Each person pays: " + billPerPerson);
System.out.println("Thankyou. Goodbye.");
System.out.println("End Program.");
}
else System.out.println("Invalid Entry");
}
}
The default value for split (because you have not initialized it with another value) is 0.0, therefore, when you do
billPerPerson = total / split;
you divide by 0.0, so you will get Infinity.
Notes:
Since your variable splitPrompt is double and computers doesn't store real values with a 100% accuracy, you shouldn't compare it with 0.0. Since this variable will store 0 or 1 for input, you can declare it as int, which will be accurate.
Try to follow Java naming conventions. Use mixedCase for methods/variables and use CamelCase for classes/interfaces.
In the method split(), you should use an if-else if-else structure:
if(splitPrompt == 0) {
...
}
else if(splitPrompt == 1) {
...
}
else {
...
}
Silly mistake.
Change
System.out.println("How many ways would you like to split the bill?
splitPrompt = scan.nextDouble();
to
System.out.println("How many ways would you like to split the bill?
split = scan.nextDouble();
since you never change split which, like all double variables, is initialized to 0.0.
Also, you should use ints where appropriate as not all of the numbers should be doubles. Or even better, use 'y' and 'n' chars.
Class TipCalc2
//Total = **bill** * (gets percentage in decimal 15 = 0.15) + **bill**
Line 18 needs to be:
total = bill * (tip / 100) + bill;
Line 36/37 needs to be:
split = splitPrompt = scan.nextInt();
billPerPerson = total / split;
//You're dividing billPerPerson = total by ZERO (split);
Line 36/37 original:
billPerPerson = total / split;
I'm trying to code a loan calculator. I seem to be having issues. I am trying to get an input from the user and validate the input. I know I am doing it wrong the problem is I'm scratching my head wondering how to do it right.
I get a red line on the d = getDouble(sc, prompt); and the i = getInt(sc, prompt); which I understand I don't have that coded correctly. I'm just unsure how to go about fixing it.
I also have to validate the continue statement which I wasn't to sure the best way to go about that and finally the instructor expects the code to be 80 lines or less which I am right about 80 lines. I guess I'm looking for a better way to do this but being new I'm scratching my head and I'm hoping someone can lend a hand.
As always I really appreciate the help.
import java.util.Scanner;
import java.text.NumberFormat;
public class LoanCalculator
{
public static double getDoubleWithinRange(Scanner sc, String prompt, double min, double max)
{
double d = 0.0;
boolean isValid = false;
while(isValid == false);
{
d = getDouble(sc, prompt);
if (d <= min)
{
System.out.println("Error! Number must be greater tha 0.0");
}
else if (d >= max)
{
System.out.println("Error number must be less than 1000000.0");
}
else
isValid = true;
}
return d;
}
public static int getIntWithinRange(Scanner sc, String prompt, int min, int max)
{
int i = 0;
boolean isvalid = false;
while(isvalid == false)
{
i = getInt(sc, prompt);
if (i <= min)
System.out.println("Error! Number must be more than 0");
else if (i >= max)
System.out.println("Error! Number must be less than 100");
else
isvalid = true;
}
}
public static void main(String[] args)
{
System.out.println("Welcome to the loan calculator");
Scanner sc = new Scanner(System.in);
String choice = "y";
while (choice.equalsIgnoreCase("y"))
{
System.out.println("DATA ENTRY");
double loanAmount = getDoubleWithinRange(sc, "Enter loan amount: ", 0.0, 1000000.0);
double interestRate = getDoubleWithinRange(sc, "Enter yearly interest rate: ", 0, 20);
int years = getIntWithinRange(sc, "Enter number of years: ", 0, 100);
int months = years * 12;
double monthlyPayment = loanAmount * interestRate/
(1 - 1/Math.pow(1 + interestRate, months));
NumberFormat currency = NumberFormat.getCurrencyInstance();
NumberFormat percent = NumberFormat.getPercentInstance();
percent.setMaximumFractionDigits(3);
System.out.println("RESULST");
System.out.println("Loan Amount" + currency.format(loanAmount));
System.out.println("Yearly interest rate: " + percent.format(interestRate));
System.out.println("Number of years: " + years);
System.out.println("Monthly payment: " + currency.format(monthlyPayment));
System.out.println();
System.out.println("Continue? (y/n): ");
choice =sc.next();
System.out.println();
}
}
}
You haven't made the implementation of your getDouble(Scanner,String) and getInt(Scanner,String) that's why you're getting the red line.
since you already have a scanner, and prompt string change it to this
System.out.print(prompt);
d = sc.nextDouble();
and for the integer
System.out.print(prompt);
i = sc.nextInt();
I think getDouble and getInt are string functions so you would have to get a string first then call those methods. However, since you have a scanner, I assume you want to use that with the nextXXX methods:
Scanner sc = new Scanner (System.in);
double d = sc.nextDouble();
You can use this complete snippet for educational purposes:
import java.util.Scanner;
class Test {
public static void main (String args[]) {
Scanner sc = new Scanner (System.in);
System.out.print("Enter your double: ");
double d = sc.nextDouble();
System.out.print("Enter your integer: ");
int i = sc.nextInt();
System.out.println("You entered: " + d + " and " + i);
}
}
Transcript:
Enter your double: 3.14159
Enter your integer: 42
You entered: 3.14159 and 42
Basically, the process is:
Instantiate a scanner, using the standard input stream.
Use print for your prompts.
Use the scanner nextXXX methods for getting the input values.
A little more assistance here, based on your comments.
In your main function, you have:
double loanAmount = getDoubleWithinRange(sc, "Enter loan amount: ", 0.0, 1000000.0)
and that function has the prototype:
public static double getDoubleWithinRange(
Scanner sc, String prompt, double min, double max)
That means those variables in the prototype will be set to the values from the call. So, to prompt for the information, you could use something like (and this is to replace the d = getDouble(sc, prompt); line):
System.out.print(prompt);
double d = sc.nextDouble();
And there you have it, you've prompted the user and input the double from them. The first line prints out the prompt, the second uses the scanner to get the input from the user.
As an aside, your checks for the minimum and maximum are good but your error messages have hard-coded values of 0 and 100K. I would suggest that you use the parameters to tailor these messages, such as changing:
System.out.println("Error! Number must be greater tha 0.0");
into:
System.out.println("Error! Number must be greater than " + min);
That way, if min or max change in future , your users won't get confused :-)
I'll leave it up to you to do a similar thing for the integer input. It is your homework, after all :-)
Alright so I'm trying to get the user to input either the word "random" or a number (0.01) for a sales tax and my prompt can only use either keybd.next() or keybd.nextDouble() so how would I easily do this?
public void calculateSalesReceipt(){
System.out.println("Enter the sales tax percentage (ex. 0.08 for 8%) or type \"random\" for a random number: ");
double tax = keybd.nextDouble();
if(tax < 0){
System.out.println("You must enter a value equal to or greater than 0!");
}else{
getFinalPricePreTax();
total = total;
taxcost = total * tax;
double finaltotal = total * taxcost;
System.out.println("Sales Receipt");
System.out.println("-------------");
for(Item currentProduct : shoppingBag){
System.out.println(currentProduct.getName() + " - " + currentProduct.getUnits() + " units " + " - $" + currentProduct.getCost());
}
System.out.println("Total cost: $" + total);
System.out.println("Total tax: $" + taxcost);
System.out.println("Total cost with tax: $" + finaltotal);
}
Thanks
Assuming keybd is a Scanner
http://download.oracle.com/javase/6/docs/api/java/util/Scanner.html
You need to use hasNextDouble() to determine if it's a double or not and then act accordingly.
Option B (though you say your requirements exclude this) is to simply read it as a String then do the conversion afterward with Double.valueOf(String) or Double.parseString(String) static methods and catching the NumberFormatException to determine validity.
Edit based on comments from OP:
System.out.println("Enter the sales tax ... blah blah");
if (keybd.hasNextDouble())
{
double tax = keybd.nextDouble();
// Do double stuff
}
else
{
// Get String and Do string stuff
}
You can use Double.parseDouble(String) to convert a string value to a double. If the string does not represent a double value, a NumberFormatException will be thrown.
double d;
if ("random".equals(string)) {
d = 4.0; // random
} else {
try {
d = Double.parseDouble(string);
} catch (NumberFormatException e) {
// !
}
}
You can use keybd.next() to grab the token as a string. Then check if its a double.
Sample code:
String input= keybd.next();
try{
Double input= Double.parseDouble(input);
//execute code with double variable
} catch (ParseException ex){
//call string handler code
}