I'm trying to get the below nested statements to work, but am having issues getting them to execute past the first statement. I tried nesting the statements but just the first if executes. Any feedback about formatting is greatly appreciated, I understand that there may be a more efficient way of achieving this, but I have to execute the code using nested statements.
package incometax;
import java.util.Scanner;
import java.text.DecimalFormat;
public class IncomeTax {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
DecimalFormat df = new DecimalFormat ("#,###,000.00");
String singleStatus = "single";
String marriedStatus = "married";
String maritalStatus = "";
double annualIncome = 0;
double taxAmount = 0;
System.out.println("Please enter your martial status: ");
maritalStatus = scnr.next();
if (maritalStatus.compareTo(singleStatus) == 0){
System.out.println("Please enter your annual income: ");
annualIncome = scnr.nextDouble();
if (annualIncome <= 30000){
taxAmount = (annualIncome * .15);
System.out.println("Based on annual income of "+ "$ " +
df.format(annualIncome) + " your tax is " + "$ " +
df.format(taxAmount));
if (annualIncome > 30000){
taxAmount = (annualIncome * .25);
System.out.println("Based on annual income of "+ "$ " +
df.format(annualIncome) +
" your tax is " + "$ " + df.format(taxAmount));
}
}
else {
if (maritalStatus.compareTo(marriedStatus) == 0){
if(annualIncome <= 30000){
taxAmount = (annualIncome * .12);
System.out.println("Based on annual income of "+ "$ "
+ df.format(annualIncome) +
" your tax is " + "$ " + df.format(taxAmount));
if(annualIncome > 30000){
taxAmount = (annualIncome * .20);
System.out.println("Based on annual income of "+
"$ " + df.format(annualIncome) +
" your tax is " + "$ " + df.format(taxAmount));
}
}
}
}
}
}
}
You are going into the first if when annualIncome <= 30000. But the condition in the nested if is annualIncome > 30000. This will always be false. Try if else instead of nested if
if (annualIncome <= 30000) {
taxAmount = (annualIncome * .15);
System.out.println("Based on annual income of "+ "$ " +
df.format(annualIncome) + " your tax is " + "$ " +
df.format(taxAmount));
}
else {
taxAmount = (annualIncome * .25);
System.out.println("Based on annual income of "+ "$ " +
df.format(annualIncome) +
" your tax is " + "$ " + df.format(taxAmount));
}
It looks like you have misplaced the parenthesis of if statement.
Try this code it should work
package incometax;
import java.util.Scanner;
import java.text.DecimalFormat;
public class IncomeTax {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
DecimalFormat df = new DecimalFormat ("#,###,000.00");
String singleStatus = "single";
String marriedStatus = "married";
String maritalStatus = "";
double annualIncome = 0;
double taxAmount = 0;
System.out.println("Please enter your martial status: ");
maritalStatus = scnr.next();
if (maritalStatus.compareTo(singleStatus) == 0){
System.out.println("Please enter your annual income: ");
annualIncome = scnr.nextDouble();
if (annualIncome <= 30000){
taxAmount = (annualIncome * .15);
System.out.println("Based on annual income of "+ "$ " +
df.format(annualIncome) + " your tax is " + "$ " +
df.format(taxAmount));
} else {
taxAmount = (annualIncome * .25);
System.out.println("Based on annual income of "+ "$ " +
df.format(annualIncome) +
" your tax is " + "$ " + df.format(taxAmount));
}
} else if (maritalStatus.compareTo(marriedStatus) == 0){
if(annualIncome <= 30000){
taxAmount = (annualIncome * .12);
System.out.println("Based on annual income of "+ "$ "
+ df.format(annualIncome) +
" your tax is " + "$ " + df.format(taxAmount));
} else {
taxAmount = (annualIncome * .20);
System.out.println("Based on annual income of "+
"$ " + df.format(annualIncome) +
" your tax is " + "$ " + df.format(taxAmount));
}
}
}
}
A decent IDE will be able to format your code to make this sort of nesting issue more apparent.
It may not be part of the question but you also have several repeated lines of code, take a look in to methods. For example the following is cleaner (note there is no validation on the marital status or the annual income)
import java.text.DecimalFormat;
import java.util.Scanner;
public class IncomeTax
{
private static final DecimalFormat DF = new DecimalFormat("#,###,000.00");
private static final String SINGLE_STATUS = "single";
private static final String MARRIED_STATUS = "married";
private static final double SINGLE_LOW_RATE = .15;
private static final double SINGLE_HIGH_RATE = .25;
private static final double MARRIED_LOW_RATE = .12;
private static final double MARRIED_HIGH_RATE = .20;
private static final int LOWER_BRACKET = 30000;
public static void main(String[] args)
{
Scanner scnr = new Scanner(System.in);
String maritalStatus;
double annualIncome;
System.out.println(
"Please enter your martial status: ");
maritalStatus = scnr.next();
System.out.println("Please enter your annual income: ");
annualIncome = scnr.nextDouble();
if (SINGLE_STATUS.equalsIgnoreCase(maritalStatus))
{
printTaxRate(annualIncome, SINGLE_LOW_RATE, SINGLE_HIGH_RATE);
} else
{
if (MARRIED_STATUS.equalsIgnoreCase(maritalStatus))
{
printTaxRate(annualIncome, MARRIED_LOW_RATE, MARRIED_HIGH_RATE);
}
}
}
private static double calcTaxAmount(double annualIncome, double taxRate)
{
return annualIncome * taxRate;
}
private static void printTaxRate(double annualIncome, double lowRate, double highRate)
{
double taxAmount;
if (annualIncome <= LOWER_BRACKET)
{
taxAmount = calcTaxAmount(annualIncome, lowRate);
} else
{
taxAmount = calcTaxAmount(annualIncome, highRate);
}
System.out.println("Based on annual income of " + "$ "
+ DF.format(annualIncome)
+ " your tax is " + "$ " + DF.format(taxAmount));
}
}
Related
It is meant to calculate interest and then put that into a table with years, interest, and new balance. For some reason the interest is not being calculated correctly and is not updating.
import java.util.Scanner;
import java.text.*;
public class Interest
{
public static void main(String[] args)
{
printIntro();
Scanner input = new Scanner(System.in);
System.out.print("Enter initial balance: ");
int balanceAmount = input.nextInt();
System.out.print("Enter interest rate: ");
double interestRate = input.nextDouble();
System.out.print("Enter the number of years: ");
int years = input.nextInt();
printTable(years, balanceAmount, interestRate);
}
public static double calcInterest(double balanceAmount, double interestRate, double years)
{
double interest = balanceAmount * Math.pow((1 + interestRate/100),years);
return interest;
}
public static void printRow(int rowNum, double balanceAmount, double interestRate)
{
System.out.println(rowNum + "\t" + balanceAmount + "\t" + "\t" + interestRate + "\t" + "\t" + (balanceAmount + interestRate));
//balanceAmount = (balanceAmount + interestRate);
}
public static void printTable(int numRows, double balanceAmount, double interestRate)
{
System.out.println("Year" + "\t" + "Balance" + "\t" + "\t" + "Interest" + "\t" + "New Balance");
System.out.println("----" + "\t" + "-------" + "\t" + "\t" + "--------" + "\t" + "-----------");
for (int i = 1; i <= numRows; i++)
{
printRow(i, balanceAmount, interestRate);
balanceAmount = (balanceAmount + interestRate);
}
}
public static void printIntro()
{
System.out.println("This program will calculate the interest "
+ "earned on a deposit over a certain amount of years.");
}
}
You should call your business logic to calculate interest as per your business requirement. That totaly depend on your business requirement.
Though for program specific it seems that You need to call your calcInterest method in printTable method, before you call your printRow method as below:
public static void printTable( final int numRows, double balanceAmount, final double interestRate ) {
System.out.println( "Year" + "\t" + "Balance" + "\t" + "\t" + "Interest" + "\t" + "New Balance" );
System.out.println( "----" + "\t" + "-------" + "\t" + "\t" + "--------" + "\t" + "-----------" );
for ( int i = 1; i <= numRows; i++ ) {
double interest = calcInterest( balanceAmount, interestRate, 1 );
printRow( i, balanceAmount, interest );
balanceAmount = ( balanceAmount + interest );
}
}
Also your formula to calculate interest is wrong. it should be
double interest = balanceAmount * Math.pow( ( 1 + interestRate / 100 ), years )-balanceAmount;
It will give out put as below:
This program will calculate the interest earned on a deposit over a certain amount of years.
This program will calculate the interest earned on a deposit over a certain amount of years.
Enter initial balance: 100
Enter interest rate: 10
Enter the number of years: 3
Year Balance Interest New Balance
---- ------- -------- -----------
1 100.0 10.000000000000014 110.00000000000001
2 110.00000000000001 23.100000000000037 133.10000000000005
3 133.10000000000005 44.05610000000007 177.15610000000012
You are not calling calcInterest.
You need to call that under the printRow method before the
System.out.println(rowNum + "\t" + balanceAmount + "\t" + "\t" + interestRate + "\t" + "\t" + (balanceAmount + interestRate));
line
Entry level java program that won't compile. Any help at all would be amazing! I really just need a quick review of my basic level code. I get errors for ints, booleans, and doubles. I've tried to rearrange them in multiple ways and i just can not get it to work. Also my Cheesy crust calculation to add it the total. Again super novice but would really enjoy the help!
import java.util.Scanner;
public class programmingassignment1 {
public static void main(String[] args) {
Scanner keyboard = new Scanner( System.in );
int pizzaLength;
int pizzaWidth;
int pizzaShape;
double pizzaDiamiter;
double pizzaToppingPrice = 0.025;
int numberOfPizzaToppings;
double pizzaSauceAndCheese = 0.036;
double pizzaDoughPrice = 0.019;
char doughType;
String dough;
int numberOfPizzas;
double pizzasBeforeTax;
int cheesyCrustInput;
int deliveryWantedInput;
int deliveryCharge;
double doughVolume;
double area;
double crustCost;
int basePrice;
int costOfPizzaWithTax;
//Shape of pizza
System.out.println("What shape of pizza requested?");
System.out.println("Enter (1) for Rectange or (2) Round?");
pizzaShape = keyboard.nextLine().charAt(0);
if(pizzaShape == 1){
System.out.println("What Length?");
pizzaLength = keyboard.nextInt();
System.out.println("What Width?");
pizzaWidth = keyboard.nextInt();
area = pizzaLength * pizzaWidth;
}
else if(pizzaShape == 2){
System.out.println("What is the Diamiter?");
pizzaDiamiter = keyboard.nextInt();
area = Math.PI * (pizzaDiamiter / 2);
}
//Volume
System.out.print("What type of dough do you want? (1)Classic Hand-Tossed, (2)Thin and Crispy, (3)Texas Toast, or (4)Pan. (enter 1,2,3, or 4.");
doughType = keyboard.nextLine().charAt(0);
if (doughType == 1) {
dough = "Classic Hand-Tossed";
doughVolume = area * .25;
}
else if (doughType == 2) {
dough = "Thin and Crispy";
doughVolume = area * .1;
}
else if (doughType == 3) {
dough = "Texas Toast";
doughVolume = area * .9;
}
else if (doughType == 4) {
dough = "Pan";
doughVolume = area * .5;
}
//Cheesey crust
if(doughType == 2){
}
else{
System.out.println("Would you like cheesy crust? (1) for yes (2) for no");
cheesyCrustInput = keyboard.nextInt();
if(cheesyCrustInput == 1){
crustCost = area * .02;
String Crust = "";
}
else{
String Crust = "NO";
}
}
//Toppings
System.out.print("Enter the number of toppings:");
numberOfPizzaToppings = keyboard.nextInt();
if(numberOfPizzaToppings == 0){
String toppings = "no";
}
else{
int toppings = numberOfPizzaToppings;
}
//Base price
basePrice = area (pizzaSauceAndCheese + (pizzaToppingPrice * numberOfPizzaToppings) + (pizzaDoughPrice * doughVolume));
//how many pizzas
System.out.print("Enter the number of pizzas being ordered:");
numberOfPizzas = keyboard.nextInt();
pizzasBeforeTax = basePrice * numberOfPizzas;
//tax
costOfPizzaWithTax = pizzasBeforeTax ( 1 + 0.07);
//delivery fee
System.out.print("Would you like delivery? (1) for yes, (2) for no.");
deliveryWantedInput = keyboard.nextInt();
if(deliveryWantedInput == 1){
String deliveryOutput = numberOfPizzas + "deliverd";
if(costOfPizzaWithTax < 10){
deliveryCharge = 3;
}
if( 10 < costOfPizzaWithTax && costOfPizzaWithTax < 20 ){
deliveryCharge = 2;
}
if(20 < costOfPizzaWithTax && costOfPizzaWithTax < 30){
deliveryCharge = 1;
}
if(costOfPizzaWithTax > 30){
deliveryCharge = 0;
}
}
else{
String deliveryOutput = "no delivery";
}
//display total
total = costOfPizzaWithTax + deliveryCharge;
System.out.println("Total Due: $" + df.format(total));
if(pizzaShape = 1){
System.out.print("User requested: Rectangular, " + pizzaWidth + "X" + pizzaLength + ", " + dough + toppings + "topping(s)"
+ Crust + "cheesy crust," + deliveryOutput + " - Program Output:");
System.out.println("Details for - Rectangular Pizza (" + pizzaWidth + "\" X " + pizzaLength + "\"):");
System.out.println( "Area: " + area );
System.out.println( "Volume:" + doughVolume);
System.out.println( "Base price: $" + basePrice);
System.out.println( "With Cheesy: $");
System.out.println( "Multi Total: $" + pizzasBeforeTax);
System.out.println( "With Tax: $" + costOfPizzaWithTax);
System.out.println( "And Delivery: $" + total);
}
else{
System.out.print("User requested: Circular, " + pizzaDiamiter + "\", " + dough + toppings + "topping(s)"
+ Crust + "cheesy crust," + deliveryOutput + " - Program Output:");
System.out.println( "Area: " + area );
System.out.println( "Volume:" + doughVolume);
System.out.println( "Base price: $" + basePrice);
System.out.println( "With Cheesy: $");
System.out.println( "Multi Total: $" + pizzasBeforeTax);
System.out.println( "With Tax: $" + costOfPizzaWithTax);
System.out.println( "And Delivery: $" + total);
}
}
}
Fixed content follows below!
import java.util.Scanner;
public class programmingassignment1 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
final double PIZZA_TOPPING_PRICE = 0.025;
final double PIZZA_SAUCE_AND_CHEESE = 0.036;
final double PIZZA_DOUGH_PRICE = 0.019;
double numberOfPizzaToppings;
double crustCost;
double basePrice;
double radiusOfPizza;
double sizeOfPizzaCrust;
double pizzasBeforeTax;
double pizzaLength = 1;
double pizzaWidth = 1;
double pizzaShape = 1;
double pizzaDiamiter = 0;
double doughType = 1;
double numberOfPizzas = 0;
double cheesyCrustInput = 0;
double deliveryWantedInput = 0;
double deliveryCharge = 0;
double doughVolume = 1;
double area = 1;
double costOfPizzaWithTax = 1;
double total = 1;
double toppings = 1;
String dough = "";
String crust = "";
String deliveryOutput;
String cheesyOutput = "";
// Shape of pizza
System.out.println("What shape of pizza requested?");
System.out.println("Enter (1) for Rectangle or (2) Round:");
pizzaShape = keyboard.nextDouble();
if (pizzaShape == 1) {
System.out.println("What Length?");
pizzaLength = keyboard.nextDouble();
System.out.println("What Width?");
pizzaWidth = keyboard.nextDouble();
area = pizzaLength * pizzaWidth;
} else if (pizzaShape == 2) {
System.out.println("What is the Diamiter?");
pizzaDiamiter = keyboard.nextDouble();
radiusOfPizza = pizzaDiamiter / 2;
area = Math.PI * radiusOfPizza * radiusOfPizza;
}
// Volume
System.out.print("What type of dough do you want? (1)Classic Hand Tossed,"
+ " (2)Thin and Crispy, (3)Texas Toast, or (4)Pan. \n(Enter 1,2,3, or 4.)");
doughType = keyboard.nextDouble();
if (doughType == 1) {
dough = "Classic Hand Tossed";
doughVolume = area * .25;
} else if (doughType == 2) {
dough = "Thin and Crispy";
doughVolume = area * .1;
} else if (doughType == 3) {
dough = "Texas Toast";
doughVolume = area * .9;
} else if (doughType == 4) {
dough = "Pan";
doughVolume = area * .5;
}
// Toppings
System.out.print("Enter the number of toppings:");
numberOfPizzaToppings = keyboard.nextDouble();
toppings = numberOfPizzaToppings;
// Base price
basePrice = area * (PIZZA_SAUCE_AND_CHEESE + PIZZA_TOPPING_PRICE * numberOfPizzaToppings)
+ PIZZA_DOUGH_PRICE * doughVolume;
// Cheesey crust
if (doughType == 2) {
cheesyOutput = " no cheesy crust";
crustCost = basePrice;
} else {
System.out.println("Would you like cheesy crust? (1) for yes (2) for no.");
cheesyCrustInput = keyboard.nextDouble();
if (cheesyCrustInput == 1 && pizzaShape == 2) {
sizeOfPizzaCrust = 2 * Math.PI * (pizzaDiamiter / 2);
crustCost = (sizeOfPizzaCrust * .02) + basePrice;
crust = "";
cheesyOutput = " cheesy crust";
} else if (cheesyCrustInput == 1 && pizzaShape == 1) {
sizeOfPizzaCrust = 2 * (pizzaLength + pizzaWidth);
crustCost = (sizeOfPizzaCrust * .02) + basePrice;
crust = "";
cheesyOutput = " cheesy crust";
} else {
crust = " NO cheesy crust";
crustCost = basePrice;
}
}
// how many pizzas
System.out.print("Enter the number of pizzas being ordered:");
numberOfPizzas = keyboard.nextDouble();
pizzasBeforeTax = crustCost * numberOfPizzas;
// tax
costOfPizzaWithTax = pizzasBeforeTax * (1 + 0.07);
// delivery fee
System.out.print("Would you like delivery? (1) for yes, (2) for no.");
deliveryWantedInput = keyboard.nextDouble();
if (deliveryWantedInput == 1) {
deliveryOutput = (int) numberOfPizzas + " pizza delivered";
if (costOfPizzaWithTax < 10) {
deliveryCharge = 3;
} else if (10 < costOfPizzaWithTax && costOfPizzaWithTax < 20) {
deliveryCharge = 2;
} else if (20 < costOfPizzaWithTax && costOfPizzaWithTax < 30) {
deliveryCharge = 1;
} else if (costOfPizzaWithTax > 30) {
deliveryCharge = 0;
}
} else {
deliveryOutput = "no delivery";
deliveryCharge = 0;
}
// display total
total = costOfPizzaWithTax + deliveryCharge;
if (pizzaShape == 1) {
System.out.print("User requested: Rectangular, " + (int) pizzaLength + "X"
+ (int) pizzaWidth + ", " + dough
+ ", " + (int) toppings + " topping(s)," + crust + cheesyOutput + ", "
+ deliveryOutput + " - Program Output:");
System.out.println("\nDetails for - Rectangular Pizza (" + pizzaLength + "\" X "
+ pizzaWidth + "\"):");
System.out.printf("Area: %.3f\n", area);
System.out.printf("Volume: %.3f\n", doughVolume);
System.out.printf("Base price: $%.2f", basePrice);
System.out.printf("\nWith Cheesy: $%.2f", crustCost);
System.out.printf("\nMulti Total: $%.2f", pizzasBeforeTax);
System.out.printf("\nWith Tax: $%.2f", costOfPizzaWithTax);
System.out.printf("\nAnd Delivery: $%.2f", total);
}
else {
System.out.print("User requested: Circular, " + (int) pizzaDiamiter + "\", "
+ dough + ", " + (int) toppings + " topping(s)," + crust + cheesyOutput
+ ", " + deliveryOutput + " - Program Output:");
System.out.println("\nDetails for - Round Pizza (" + pizzaDiamiter + "\" diameter):");
System.out.printf("Area: %.3f\n", area);
System.out.printf("Volume: %.3f\n", doughVolume);
System.out.printf("Base price: $%.2f", basePrice);
System.out.printf("\nWith Cheesy: $%.2f", crustCost);
System.out.printf("\nMulti Total: $%.2f", pizzasBeforeTax);
System.out.printf("\nWith Tax: $%.2f", costOfPizzaWithTax);
System.out.printf("\nAnd Delivery: $%.2f", total);
}
}
}
Your problem is related to scopes:
if ( condition ) {
String topping = "topping";
}
System.out.println(topping);
Will not compile. (Your code is a bit more broad, but still)
The problem here is that topping is a local variable in the if-block, once the if-block is terminated, the variable doesn't exist anymore.
You need to fix it to something like:
String topping = "default";
if ( condition ) {
topping = "topping";
}
System.out.println(topping);
Here is the error free code you need. You just need to create the methods and write your logic in it.
import java.util.Scanner;
public class pizzas {
public static void main(String[] args) {
Scanner keyboard = new Scanner( System.in );
int pizzaLength = 0;
int pizzaWidth = 0;
int pizzaShape;
double pizzaDiamiter = 0;
double pizzaToppingPrice = 0.025;
int numberOfPizzaToppings;
double pizzaSauceAndCheese = 0.036;
double pizzaDoughPrice = 0.019;
char doughType;
String dough = null;
int numberOfPizzas;
double pizzasBeforeTax;
int cheesyCrustInput;
int deliveryWantedInput;
int deliveryCharge = 0;
double doughVolume = 0;
double area = 0;
double crustCost;
int basePrice;
int costOfPizzaWithTax;
//Shape of pizza
System.out.println("What shape of pizza requested?");
System.out.println("Enter (1) for Rectange or (2) Round?");
pizzaShape = keyboard.nextLine().charAt(0);
if(pizzaShape == 1){
System.out.println("What Length?");
pizzaLength = keyboard.nextInt();
System.out.println("What Width?");
pizzaWidth = keyboard.nextInt();
area = pizzaLength * pizzaWidth;
}
else if(pizzaShape == 2){
System.out.println("What is the Diamiter?");
pizzaDiamiter = keyboard.nextInt();
area = Math.PI * (pizzaDiamiter / 2);
}
//Volume
System.out.print("What type of dough do you want? (1)Classic Hand-Tossed, (2)Thin and Crispy, (3)Texas Toast, or (4)Pan. (enter 1,2,3, or 4.");
doughType = keyboard.nextLine().charAt(0);
String Crust = "";
String deliveryOutput="";
if (doughType == 1) {
dough = "Classic Hand-Tossed";
doughVolume = area * .25;
}
else if (doughType == 2) {
dough = "Thin and Crispy";
doughVolume = area * .1;
}
else if (doughType == 3) {
dough = "Texas Toast";
doughVolume = area * .9;
}
else if (doughType == 4) {
dough = "Pan";
doughVolume = area * .5;
}
//Cheesey crust
if(doughType == 2){
}
else{
System.out.println("Would you like cheesy crust? (1) for yes (2) for no");
cheesyCrustInput = keyboard.nextInt();
if(cheesyCrustInput == 1){
crustCost = area * .02;
Crust = "";
}
else{
Crust = "NO";
}
}
//Toppings
System.out.print("Enter the number of toppings:");
numberOfPizzaToppings = keyboard.nextInt();
int toppings;
if(numberOfPizzaToppings == 0){
toppings = 0;
}
else{
toppings = numberOfPizzaToppings;
}
//Base price
basePrice = area (pizzaSauceAndCheese + (pizzaToppingPrice * numberOfPizzaToppings) + (pizzaDoughPrice * doughVolume));
//how many pizzas
System.out.print("Enter the number of pizzas being ordered:");
numberOfPizzas = keyboard.nextInt();
pizzasBeforeTax = basePrice * numberOfPizzas;
//tax
costOfPizzaWithTax = pizzasBeforeTax ( 1 + 0.07);
//delivery fee
System.out.print("Would you like delivery? (1) for yes, (2) for no.");
deliveryWantedInput = keyboard.nextInt();
if(deliveryWantedInput == 1){
deliveryOutput = numberOfPizzas + "deliverd";
if(costOfPizzaWithTax < 10){
deliveryCharge = 3;
}
if( 10 < costOfPizzaWithTax && costOfPizzaWithTax < 20 ){
deliveryCharge = 2;
}
if(20 < costOfPizzaWithTax && costOfPizzaWithTax < 30){
deliveryCharge = 1;
}
if(costOfPizzaWithTax > 30){
deliveryCharge = 0;
}
}
else{
deliveryOutput = "no delivery";
}
//display total
int total = costOfPizzaWithTax + deliveryCharge;
//System.out.println("Total Due: $" + df.format(total));
if(pizzaShape == 1){
System.out.print("User requested: Rectangular, " + pizzaWidth + "X"
+ pizzaLength + ", " + dough + toppings + "topping(s)"
+ Crust + "cheesy crust," + deliveryOutput + " - Program Output:");
System.out.println("Details for - Rectangular Pizza (" + pizzaWidth + "\" X " + pizzaLength + "\"):");
System.out.println( "Area: " + area );
System.out.println( "Volume:" + doughVolume);
System.out.println( "Base price: $" + basePrice);
System.out.println( "With Cheesy: $");
System.out.println( "Multi Total: $" + pizzasBeforeTax);
System.out.println( "With Tax: $" + costOfPizzaWithTax);
System.out.println( "And Delivery: $" + total);
}
else{
System.out.print("User requested: Circular, " + pizzaDiamiter + "\", " + dough + toppings + "topping(s)"
+ Crust + "cheesy crust," + deliveryOutput + " - Program Output:");
System.out.println( "Area: " + area );
System.out.println( "Volume:" + doughVolume);
System.out.println( "Base price: $" + basePrice);
System.out.println( "With Cheesy: $");
System.out.println( "Multi Total: $" + pizzasBeforeTax);
System.out.println( "With Tax: $" + costOfPizzaWithTax);
System.out.println( "And Delivery: $" + total);
}
}
Methods:
private static int pizzasBeforeTax(double d) {
// TODO Auto-generated method stub
return 0;
}
private static int area(double d) {
// TODO Auto-generated method stub
return 0;
}
Issues in your code:
1. You have not initialized the variables you have used.
2. You have declared the variables in if and else clause. When you are planning to re-use the variables, never initialize them inside as their scope is restricted to the block.
3. Also, you have used the same variable name toppings as String and int .
I am a beginner and not tried the following program which is giving me repeated output.. I have to end the program manually in eclipse. Not able to figure out the problem. Please advice. Any other tips are welcome.
import java.util.Scanner;
public class Sales_Amount {
public static void main(String[] args) {
final double Base_Salary = 25000;
double Commission = 0;
double Total_Salary;
double X;
double Y;
Scanner input = new Scanner(System. in );
System.out.print("Enter Sales Amount: ");
double Sales = input.nextDouble();
while (Commission < 25001) {
if (Sales <= 5000); {
Total_Salary = Base_Salary + (0.08 * Sales);
System.out.print(" Total Salary for " + Sales + "worth of Sales is: " + Total_Salary);
}
if (Sales > 5000 && Sales < 10001); {
X = Sales - 5000;
Total_Salary = Base_Salary + (0.08 * 5000) + (0.10 * X);
System.out.print(" Total Salary for " + Sales + "worth of Sales is: " + Total_Salary);
}
if (Sales > 10001); {
Y = Sales - 10000;
Total_Salary = Base_Salary + (.08 * 5000) + (.10 * 10000) + (.12 * Y);
System.out.print(" Total Salary for " + Sales + "worth of Sales is: " + Total_Salary);
}
}
}
}
Add commission++ before the end of the loop.
The balance should take the initial balance and subtract or add the transamt depending on the tcode(1 is a withdraw and 2 is a deposit).
Service charges are $0.10 for a deposit and $0.15 for a check. If a check forces the balance to drop below $500.00, a service charge of $5.00 is assessed but only for the first time this happens. Anytime the balance drops below $50.00, the program should print a warning message. If a check results in a negative balance, an additional service charge of $10.00 should be assessed.
The decimal format for the balance should be "00000.##" for positive and "(00000.##)". I do not know how put the second one.
import java.text.DecimalFormat;
import javax.swing.JOptionPane;
public class Main {
//global variables
CheckingAccount c;
public double balance;
public double totalServiceCharge;
public static void main (String[] args)
{
// defines local variables
String iBalance, transATM, message, transCode;
int tcode;
double transatm, ibalance, currentservicecharge, fee = 0;
// get initial balance from the user
// perform in a loop until the trans code = 0
// get the trans code from the user and process it with appropriate helper method
// When loop ends show final balance to user.
iBalance = JOptionPane.showInputDialog ("Enter the initial balance: ");
ibalance = Double.parseDouble(iBalance);
CheckingAccount c = new CheckingAccount(ibalance);
DecimalFormat df = new DecimalFormat("#####.00");
do
{
transCode = JOptionPane.showInputDialog ("Enter the trans code: ");
tcode = Integer.parseInt(transCode);
if(tcode == 1)
{
transATM = JOptionPane.showInputDialog ("Enter the trans atm: ");
transatm = Double.parseDouble(transATM);
currentservicecharge = 0.15;
message = "Transaction: Check in amount of $" + transatm + "\n" +
"Current balance: " + c.getBalance() + "\n" +
"Service Charge: Check --- charge $ " + currentservicecharge + "\n" +
"Service Charge: " + fee + "\n" +
"Total Service Charge: " + c.getServiceCharge();
JOptionPane.showMessageDialog (null, message + df);
}
else if(tcode == 2)
{
transATM = JOptionPane.showInputDialog ("Enter the trans atm: ");
transatm = Double.parseDouble(transATM);
currentservicecharge = 0.10;
message = "Transaction: Deposit in amount of $" + transatm + "\n" +
"Current balance: " + c.getBalance() + "\n" +
"Service Charge: Check --- charge $ " + currentservicecharge + "\n" +
"Service Charge: " + fee + "\n" +
"Total Service Charge: " + c.getServiceCharge();
JOptionPane.showMessageDialog (null, message + df);
}
}
while (tcode != 0);
message = "Transaction: End" + "\n" +
"Current Balance: " + ibalance + "\n" +
"Total Service Charge: " + c.getServiceCharge() + "\n" +
"Final Balance: " + c.getBalance();
JOptionPane.showMessageDialog (null, message + df);
}
public int getTransCode(int tcode)
{
return tcode;
}
public double getTransAmt(double transatm)
{
return transatm;
}
public double processCheck(double currentservicecharge)
{
return currentservicecharge;
}
public double processDeposit(double currentservicecharge)
{
return currentservicecharge;
}
public double processFee(double fee)
{
return fee;
}
public void setServiceCharge(double currentServiceCharge)
{
totalServiceCharge += currentServiceCharge;
}
public void penatlyCharge(double fee, double currentservicecharge, double transatm, String message, CheckingAccount c)
{
if(c.getBalance() < 500.00)
{
fee = 5.00;
currentservicecharge += fee;
message = "Service Charge: " + fee + "\n" +
"Warning : Balance below $500" ;
}
else if(c.getBalance() < 0.00)
{
fee = 10.00;
currentservicecharge += fee;
message = "Service Charge: " + fee + "\n" +
"Warning : Balance below $0";
}
else if(c.getBalance() < 50.00)
message = "Service Charge: " + fee + "\n" +
"Warning : Balance below $50" ;
}
}
public class CheckingAccount {
private double balance;
private double totalServiceCharge;
public CheckingAccount()
{
balance = 0;
totalServiceCharge = 0;
}
public CheckingAccount(double ibalance)
{
balance = ibalance;
}
public void setBalance(double transamt, int tcode)
{
if(tcode == 1)
{
double newBalance = balance - transamt;
balance = newBalance;
}
else if(tcode == 2)
{
double newBalance = balance + transamt;
balance = newBalance;
}
}
public double getBalance()
{
return balance;
}
public double getServiceCharge()
{
return totalServiceCharge;
}
}
Have you tried something like:
if (amount >= 0.0) {
showMessageDialog(amount);
} else {
showMessageDialog('(' + Math.abs(amount) + ')');
}
That is simplified, but it gets the idea across.
I've written a program in Java that does a series of calculations, basically a payroll program for four different types of employees. I'm having an issue trying to make it NOT exit after the input is completed.
For example: The user is asked how many employees are in the company. From there it should start asking what employee #1's type is (manager, hourly, etc...) then keep asking until the total employees are met, say for example 4. After each input it's okay for the employee's name and information to output.
Here's what I have thus far, which is an almost complete, working program. The only thing left is the part I described above.
Any resources to help me work out the solution are more valuable than rewriting my code.
Thanks!
import java.util.Scanner;
import java.text.DecimalFormat;
public class PayrollSwitch {
public static void main(String[] args) {
// First input group
int employeeType; // 1-4 (Manager, Hourly, Commissioned, Pieceworker)
int compSize; // Company size (4 - 10)
int hoursWrkd; // Whole Number, no partial hours.
String employeeName; // Name of the Employee
// Pay for each worker type
double rateManagerWrkr = 800.00;// Fixed weekly salary
double managerBonus = 750.00; // $750.00 bonus for manager
double rateHourWrkr; // Hourly + overtime > 40 = 1.5 time hourly rate
double hourOvertime = 1.5; // If hoursWrkd > 40
double hourOvertimeStore; // Stores value
double rateCommWrkr = 650.00; // Fixed weekly salary
double commBonus = 250.00; // $250.00 bonus for commissioned worker
double commWklySal; // 5.7% time weekly salary (650.00 * 5.7)
double ratePieceWrkr = 400.00; // Fixed weekly salary
// Deductions
double medicalDues = 20.00; // $20.00 per pay period
double fedTax = 0.30; // 30% of gross
double socialSec = 0.05; // 5% of gross
double deductDues;
double fedTaxFinal;
double socialSecFinal;
// Totals
double managerGross;
double managerNet;
double hourGross;
double hourNet;
double commGross;
double commNet;
double pieceGross;
double pieceNet;
// Convert decimals to match ####.## place ($9999.99)
DecimalFormat df = new DecimalFormat("####.##");
String employeeTitle;
Scanner input = new Scanner(System.in);
System.out.print("Enter an employee paycode (1-4): ");
employeeType = input.nextInt();
switch (employeeType)
{
case 1:
{
employeeTitle = "Manager";
System.out.println("You selected manager!");
System.out.print("What's your name? :");
employeeName = input.next();
System.out.print("Enter the amount of hours worked this week: ");
hoursWrkd = input.nextInt();
System.out.println("Name: " + employeeName);
System.out.println("Title: " + employeeTitle);
System.out.println("Type: " + employeeType);
System.out.println("Hours worked: " + hoursWrkd);
managerGross = rateManagerWrkr + managerBonus;
System.out.println("Gross pay: $" + df.format(managerGross));
System.out.println("Federal Tax: $" + df.format(managerGross * fedTax));
System.out.println("Social Security: $" + df.format(managerGross * socialSec));
System.out.println("Medical: $" + df.format(medicalDues));
fedTaxFinal = managerGross * fedTax;
socialSecFinal = managerGross * socialSec;
deductDues = (fedTaxFinal + socialSecFinal + medicalDues);
managerNet = (managerGross - deductDues);
System.out.println("Net pay: $" + df.format(managerNet));
}
break;
case 2:
{
employeeTitle = "Hourly";
System.out.println("You selected hourly!");
System.out.print("What's your name? :");
employeeName = input.next();
System.out.print("Enter the amount of hours worked this week: ");
hoursWrkd = input.nextInt();
System.out.print("Enter hourly rate: $");
rateHourWrkr = input.nextDouble();
hourGross = rateHourWrkr * hoursWrkd;
System.out.println("Name: " + employeeName);
System.out.println("Title: " + employeeTitle);
System.out.println("Type: " + employeeType);
// Begin checking hours worked
if (hoursWrkd > 40)
{
hourOvertimeStore = (hoursWrkd - 40) * rateHourWrkr * hourOvertime;
System.out.println("Hours worked: " + hoursWrkd);
System.out.println("Overtime hours: " + (hoursWrkd - 40));
System.out.println("Gross pay: $" + df.format(hourGross + hourOvertimeStore));
System.out.println("Federal Tax: $" + df.format(hourGross * fedTax));
System.out.println("Social Security: $" + df.format(hourGross * socialSec));
System.out.println("Medical: $" + df.format(medicalDues));
fedTaxFinal = hourGross * fedTax;
socialSecFinal = hourGross * socialSec;
deductDues = (fedTaxFinal + socialSecFinal + medicalDues);
hourNet = (hourGross - deductDues);
System.out.println("Net pay: $" + df.format(hourNet));
}
else
{
hourGross = hoursWrkd * rateHourWrkr;
hourOvertimeStore = 0;
System.out.println("Hours worked: " + hoursWrkd);
System.out.println("Gross pay: $" + df.format(hourGross + hourOvertimeStore));
System.out.println("Federal Tax: $" + df.format(hourGross * fedTax));
System.out.println("Social Security: $" + df.format(hourGross * socialSec));
System.out.println("Medical: $" + df.format(medicalDues));
fedTaxFinal = hourGross * fedTax;
socialSecFinal = hourGross * socialSec;
deductDues = (fedTaxFinal + socialSecFinal + medicalDues);
hourNet = (hourGross - deductDues);
System.out.println("Net pay: " + df.format(hourNet));
}
}
break;
case 3:
{
employeeTitle = "Commission";
System.out.println("You selected commission!");
System.out.print("What's your name? :");
employeeName = input.next();
System.out.print("Enter the amount of hours worked this week: ");
hoursWrkd = input.nextInt();
System.out.println("Name: " + employeeName);
System.out.println("Title: " + employeeTitle);
System.out.println("Type: " + employeeType);
System.out.println("Hours worked: " + hoursWrkd);
commGross = rateCommWrkr + commBonus;
commWklySal = (0.057 * rateCommWrkr);
System.out.println("Commission made: $" + df.format(commWklySal));
System.out.println("Gross pay: $" + df.format(commWklySal + commGross));
System.out.println("Federal Tax: $" + df.format((commWklySal + commGross) * fedTax));
System.out.println("Social Security: $" + df.format((commWklySal + commGross) * socialSec));
System.out.println("Medical: $" + df.format(medicalDues));
fedTaxFinal = (commWklySal + commGross) * fedTax;
socialSecFinal = (commWklySal + commGross) * socialSec;
deductDues = (fedTaxFinal + socialSecFinal + medicalDues);
commNet = (commWklySal + commGross) - deductDues;
System.out.println("Net pay: $" + df.format(commNet));
}
break;
case 4:
{
employeeTitle = "Pieceworker";
System.out.println("You selected pieceworker!");
System.out.print("What's your name? :");
employeeName = input.next();
System.out.print("Enter the amount of hours worked this week: ");
hoursWrkd = input.nextInt();
System.out.println("Name: " + employeeName);
System.out.println("Title: " + employeeTitle);
System.out.println("Type: " + employeeType);
System.out.println("Hours worked: " + hoursWrkd);
pieceGross = ratePieceWrkr;
System.out.println("Gross pay: $" + df.format(pieceGross));
System.out.println("Federal Tax: $" + df.format(pieceGross * fedTax));
System.out.println("Social Security: $" + df.format(pieceGross * socialSec));
System.out.println("Medical: $" + df.format(medicalDues));
pieceNet = pieceGross - fedTax - socialSec - medicalDues;
System.out.println("Net pay: $" + df.format(pieceNet));
}
break;
}
}
}
You are not asking the "Number of Employees" from the User in your code.Hope this is what you want.
package test;
import java.util.Scanner;
import java.text.DecimalFormat;
public class test {
public static void main(String[] args) {
// First input group
int employeeType; // 1-4 (Manager, Hourly, Commissioned, Pieceworker)
int compSize; // Company size (4 - 10)
int hoursWrkd; // Whole Number, no partial hours.
String employeeName; // Name of the Employee
// Pay for each worker type
double rateManagerWrkr = 800.00;// Fixed weekly salary
double managerBonus = 750.00; // $750.00 bonus for manager
double rateHourWrkr; // Hourly + overtime > 40 = 1.5 time hourly rate
double hourOvertime = 1.5; // If hoursWrkd > 40
double hourOvertimeStore; // Stores value
double rateCommWrkr = 650.00; // Fixed weekly salary
double commBonus = 250.00; // $250.00 bonus for commissioned worker
double commWklySal; // 5.7% time weekly salary (650.00 * 5.7)
double ratePieceWrkr = 400.00; // Fixed weekly salary
// Deductions
double medicalDues = 20.00; // $20.00 per pay period
double fedTax = 0.30; // 30% of gross
double socialSec = 0.05; // 5% of gross
double deductDues;
double fedTaxFinal;
double socialSecFinal;
// Totals
double managerGross;
double managerNet;
double hourGross;
double hourNet;
double commGross;
double commNet;
double pieceGross;
double pieceNet;
// Convert decimals to match ####.## place ($9999.99)
DecimalFormat df = new DecimalFormat("####.##");
String employeeTitle;
int numberOfEmployees=0;
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of Employees in your company ");
numberOfEmployees = input.nextInt();
for(int i=0;i<numberOfEmployees;i++)
{
System.out.println("----------------------------------------------");
System.out.println("Enter Information for Employee Number " + Integer.toString(i+1));
System.out.print("Enter an employee paycode (1-4): ");
employeeType = input.nextInt();
switch (employeeType)
{
case 1:
{
employeeTitle = "Manager";
System.out.println("You selected manager!");
System.out.print("What's your name? :");
employeeName = input.next();
System.out.print("Enter the amount of hours worked this week: ");
hoursWrkd = input.nextInt();
System.out.println("Name: " + employeeName);
System.out.println("Title: " + employeeTitle);
System.out.println("Type: " + employeeType);
System.out.println("Hours worked: " + hoursWrkd);
managerGross = rateManagerWrkr + managerBonus;
System.out.println("Gross pay: $" + df.format(managerGross));
System.out.println("Federal Tax: $" + df.format(managerGross * fedTax));
System.out.println("Social Security: $" + df.format(managerGross * socialSec));
System.out.println("Medical: $" + df.format(medicalDues));
fedTaxFinal = managerGross * fedTax;
socialSecFinal = managerGross * socialSec;
deductDues = (fedTaxFinal + socialSecFinal + medicalDues);
managerNet = (managerGross - deductDues);
System.out.println("Net pay: $" + df.format(managerNet));
}
break;
case 2:
{
employeeTitle = "Hourly";
System.out.println("You selected hourly!");
System.out.print("What's your name? :");
employeeName = input.next();
System.out.print("Enter the amount of hours worked this week: ");
hoursWrkd = input.nextInt();
System.out.print("Enter hourly rate: $");
rateHourWrkr = input.nextDouble();
hourGross = rateHourWrkr * hoursWrkd;
System.out.println("Name: " + employeeName);
System.out.println("Title: " + employeeTitle);
System.out.println("Type: " + employeeType);
// Begin checking hours worked
if (hoursWrkd > 40)
{
hourOvertimeStore = (hoursWrkd - 40) * rateHourWrkr * hourOvertime;
System.out.println("Hours worked: " + hoursWrkd);
System.out.println("Overtime hours: " + (hoursWrkd - 40));
System.out.println("Gross pay: $" + df.format(hourGross + hourOvertimeStore));
System.out.println("Federal Tax: $" + df.format(hourGross * fedTax));
System.out.println("Social Security: $" + df.format(hourGross * socialSec));
System.out.println("Medical: $" + df.format(medicalDues));
fedTaxFinal = hourGross * fedTax;
socialSecFinal = hourGross * socialSec;
deductDues = (fedTaxFinal + socialSecFinal + medicalDues);
hourNet = (hourGross - deductDues);
System.out.println("Net pay: $" + df.format(hourNet));
}
else
{
hourGross = hoursWrkd * rateHourWrkr;
hourOvertimeStore = 0;
System.out.println("Hours worked: " + hoursWrkd);
System.out.println("Gross pay: $" + df.format(hourGross + hourOvertimeStore));
System.out.println("Federal Tax: $" + df.format(hourGross * fedTax));
System.out.println("Social Security: $" + df.format(hourGross * socialSec));
System.out.println("Medical: $" + df.format(medicalDues));
fedTaxFinal = hourGross * fedTax;
socialSecFinal = hourGross * socialSec;
deductDues = (fedTaxFinal + socialSecFinal + medicalDues);
hourNet = (hourGross - deductDues);
System.out.println("Net pay: " + df.format(hourNet));
}
}
break;
case 3:
{
employeeTitle = "Commission";
System.out.println("You selected commission!");
System.out.print("What's your name? :");
employeeName = input.next();
System.out.print("Enter the amount of hours worked this week: ");
hoursWrkd = input.nextInt();
System.out.println("Name: " + employeeName);
System.out.println("Title: " + employeeTitle);
System.out.println("Type: " + employeeType);
System.out.println("Hours worked: " + hoursWrkd);
commGross = rateCommWrkr + commBonus;
commWklySal = (0.057 * rateCommWrkr);
System.out.println("Commission made: $" + df.format(commWklySal));
System.out.println("Gross pay: $" + df.format(commWklySal + commGross));
System.out.println("Federal Tax: $" + df.format((commWklySal + commGross) * fedTax));
System.out.println("Social Security: $" + df.format((commWklySal + commGross) * socialSec));
System.out.println("Medical: $" + df.format(medicalDues));
fedTaxFinal = (commWklySal + commGross) * fedTax;
socialSecFinal = (commWklySal + commGross) * socialSec;
deductDues = (fedTaxFinal + socialSecFinal + medicalDues);
commNet = (commWklySal + commGross) - deductDues;
System.out.println("Net pay: $" + df.format(commNet));
}
break;
case 4:
{
employeeTitle = "Pieceworker";
System.out.println("You selected pieceworker!");
System.out.print("What's your name? :");
employeeName = input.next();
System.out.print("Enter the amount of hours worked this week: ");
hoursWrkd = input.nextInt();
System.out.println("Name: " + employeeName);
System.out.println("Title: " + employeeTitle);
System.out.println("Type: " + employeeType);
System.out.println("Hours worked: " + hoursWrkd);
pieceGross = ratePieceWrkr;
System.out.println("Gross pay: $" + df.format(pieceGross));
System.out.println("Federal Tax: $" + df.format(pieceGross * fedTax));
System.out.println("Social Security: $" + df.format(pieceGross * socialSec));
System.out.println("Medical: $" + df.format(medicalDues));
pieceNet = pieceGross - fedTax - socialSec - medicalDues;
System.out.println("Net pay: $" + df.format(pieceNet));
}
break;
}
}
System.out.println("Thank you for using this Application");
}
}
It would appear that you need a loop, I suggest you use a do-while loop - that is, something like,
boolean stop = false;
do {
// as before
// set stop to true to end the loop.
} while (!stop);