Formatting decimal point in JOptionPane.showMessageDialog - java

My code has been an evolving process and the end game is to implement a UI using JOptionPane to my previous iteration. I successfully formatted an output to a 2 decimal place using String.format("Text goes here %.2f", variable) but when I try to carry this method over to my iteration of code using JOptionPane it crashes the program.
Here is my code
import javax.swing.JOptionPane;
public class Ass1d2
{
public static void main(String [] args)
{
final int N = 7;
String taxPayerName;
int taxPayerIncome = 0;
double maxTax = 0.0;
String maxTaxName = "";
JOptionPane.showMessageDialog(null, "Welcome to use Tax Computation System");
for(int i = 0; i < N; i++)
{
taxPayerName = (String)JOptionPane.showInputDialog(null, "Enter tax payers name");
taxPayerIncome = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter income for the tax payer"));
double tax = computeTax(taxPayerIncome);
if (taxPayerIncome > maxTax){
maxTax = tax;
maxTaxName = taxPayerName;
}
JOptionPane.showMessageDialog(null, "The tax that " + taxPayerName + " owes is $" + tax));
}
JOptionPane.showMessageDialog(null, "The maximum tax is $" + maxTax) + " paid by " + maxTaxName);
}
private static double computeTax(int taxPayerIncome)
{
double tax = 0.0;
if (taxPayerIncome < 18200)
tax = 0;
else if (taxPayerIncome < 37000)
tax = (taxPayerIncome - 18200) * 0.19;
else if (taxPayerIncome < 87000)
tax = 3572 + (taxPayerIncome - 37000) * 0.325;
else if (taxPayerIncome < 180000)
tax = 19822 + (taxPayerIncome - 87000) * 0.37;
else
tax = 54232 + (taxPayerIncome - 180000) * 0.47;
return tax;
}
}
How do I format the two showMessageDialog to produce a two decimal floating point result? I've been scouring guides for the past hour and it's just not clicking. Very frustrating that this is the final roadblock. Thanks.

Well I must have done a typo in my other attempts as I have it working now. Awkward. Attached updated code with working floating point result for future reference.
import javax.swing.JOptionPane;
public class Ass1d2
{
public static void main(String [] args)
{
final int N = 3;
String taxPayerName;
int taxPayerIncome = 0;
double maxTax = 0.0;
String maxTaxName = "";
JOptionPane.showMessageDialog(null, "Welcome to use Tax Computation System");
for(int i = 0; i < N; i++)
{
taxPayerName = (String)JOptionPane.showInputDialog(null, "Enter tax payers name");
taxPayerIncome = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter income for the tax payer"));
double tax = computeTax(taxPayerIncome);
if (taxPayerIncome > maxTax){
maxTax = tax;
maxTaxName = taxPayerName;
}
JOptionPane.showMessageDialog(null, "The tax that " + taxPayerName + " owes is $" + String.format("%.2f", tax));
}
JOptionPane.showMessageDialog(null, "The maximum tax is $" + String.format("%.2f", maxTax) + " paid by " + maxTaxName);
}
private static double computeTax(int taxPayerIncome)
{
double tax = 0.0;
if (taxPayerIncome < 18200)
tax = 0;
else if (taxPayerIncome < 37000)
tax = (taxPayerIncome - 18200) * 0.19;
else if (taxPayerIncome < 87000)
tax = 3572 + (taxPayerIncome - 37000) * 0.325;
else if (taxPayerIncome < 180000)
tax = 19822 + (taxPayerIncome - 87000) * 0.37;
else
tax = 54232 + (taxPayerIncome - 180000) * 0.47;
return tax;
}
}

Related

Finding out how many times a user is processed?

I'm having some trouble with a part of an assignment. I have to see how many times an employee is processed in my program, after the loop runs once it asks the user if they would like to process another. If they enter y for yes and then they enter n for end after the second employee calculation. I want it to say "Number of employees processed: 2". How could I do this?
package paytime;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
String firstName, lastName, choice;
double hoursWorked, hourlyWage;
boolean processAnotherEmployee = true;
Employee one = new Employee();
while(true)
{
if (processAnotherEmployee)
{
System.out.print("Enter Y to process employee or any other key to end: ");
choice = scn.next();
if (choice.equalsIgnoreCase("Y"))
{
System.out.print("Enter employee number: ");
int number = scn.nextInt();
while (!one.findEmpNumber(number))
{
System.out.print("Invlaid, enter a proper employee number: ");
number = scn.nextInt();
}
System.out.print("Enter first name: ");
firstName = scn.next();
System.out.print("Enter last name: ");
lastName = scn.next();
System.out.print("Enter hours worked: ");
hoursWorked = scn.nextDouble();
while (hoursWorked < 0)
{
System.out.print("Negative hours not allowed. Enter hours worked: ");
hoursWorked = scn.nextDouble();
}
System.out.print("Enter hourly wage: $");
hourlyWage = scn.nextDouble();
while (hourlyWage < 0 || hourlyWage > 100)
{
System.out.print("Negative wage is not allowed or wage entered is to high. Enter hourley wage: $");
hourlyWage = scn.nextDouble();
}
double overtimeHours = hoursWorked - 40;
double overtimeWage = hourlyWage * 1.5;
System.out.println(" ");
if (hoursWorked <= 40.0)
{
System.out.println("Worker " + number + " Paycheck Information: ");
System.out.println("Name is: " + firstName + " " + lastName);
System.out.println("Weekly Pay is: " + one.callWeeklyPay(hoursWorked, hourlyWage));
System.out.println("Income Taxes is: " + one.callIncomeTax());
System.out.println("Net Pay is: " + one.callNetPay());
}
else if (hoursWorked > 40.0)
{
System.out.println("Worker " + number + " Paycheck Information: ");
System.out.println("Name is: " + firstName + " " + lastName);
System.out.println("Weekly Pay is: " + one.callWeeklyPay(hoursWorked, hourlyWage));
System.out.println("Income Taxes is: " + one.callIncomeTax());
System.out.println("Net Pay is: " + one.callNetPay());
System.out.println(" ");
System.out.println("Worker " + number + " Overtime Calculation: ");
System.out.println("Overtime Pay is: " + one.callOvertimePay(overtimeHours, overtimeWage, hourlyWage, hoursWorked));
System.out.println("Overtime Income Tax is: " + one.callOvertimeTax());
System.out.println("Overtime Net Pay is: " + one.callOvertimeNetPay());
System.out.println("Total Net Pay is: " + one.callTotalNetPay());
System.out.println(" ");
}
}
else if (!choice.equalsIgnoreCase("Y"))
{
processAnotherEmployee = false;
System.out.println("Total number of Employees processed: ");
System.out.println(" ");
System.out.println("End of program");
break;
}
}
}
}
}
and
package paytime;
public class Employee {
private int empNumbers [] = {101, 103, 106, 109, 110, 113, 116, 118, 120};
public double weeklyPay, hoursWorked, hourlyWage, incomeTax, netPay,
overtimePay, overtimeHours, overtimeWage, overtimeIncomeTax,
overtimeNetPay, totalNetPay;
public boolean findEmpNumber(int number)
{
boolean found = false;
for (int sub = 0; sub < empNumbers.length; sub++)
{
if (number == empNumbers[sub])
{
found = true;
break;
}
}
return found;
}
private void calculateWeeklyPay(double hoursWorked, double hourlyWage) {
if (hoursWorked > 40)
{
hoursWorked = 40;
weeklyPay = hoursWorked * hourlyWage;
}
else
{
weeklyPay = hoursWorked * hourlyWage;
}
}
public double callWeeklyPay(double hoursWorked, double hourlyWage) {
calculateWeeklyPay(hoursWorked, hourlyWage);
return weeklyPay;
}
private void calculateIncomeTax() {
if (weeklyPay > 0.0 && weeklyPay <= 300.0)
{
incomeTax = weeklyPay * 0.10;
}
else if (weeklyPay > 300.1 && weeklyPay <= 400.0)
{
incomeTax = weeklyPay * 0.12;
}
else if (weeklyPay > 400.1 && weeklyPay <= 500.0)
{
incomeTax = weeklyPay * 0.15;
}
else if (weeklyPay > 500.1)
{
incomeTax = weeklyPay * 0.20;
}
}
public double callIncomeTax() {
calculateIncomeTax();
return incomeTax;
}
private void calculateNetPay() {
netPay = weeklyPay - incomeTax;
}
public double callNetPay() {
calculateNetPay();
return netPay;
}
private void calculateOvertimePay(double overtimeHours, double overtimeWage, double hourlyWage, double hoursWorked) {
overtimePay = overtimeHours * overtimeWage;
}
public double callOvertimePay(double overtimeHours, double overtimeWage, double hourlyWage, double hoursWorked) {
calculateOvertimePay(overtimeHours, overtimeWage, hourlyWage, hoursWorked);
return overtimePay;
}
private void calculateOvertimeTax() {
overtimeIncomeTax = overtimePay * 0.25;
}
public double callOvertimeTax() {
calculateOvertimeTax();
return overtimeIncomeTax;
}
private void calculateOvertimeNetPay() {
overtimeNetPay = overtimePay - overtimeIncomeTax;
}
public double callOvertimeNetPay() {
calculateOvertimeNetPay();
return overtimeNetPay;
}
private void calculateTotalNetPay() {
totalNetPay = netPay + overtimeNetPay;
}
public double callTotalNetPay() {
calculateTotalNetPay();
return totalNetPay;
}
}
You can achieve this by simply having "int employeesProcessed = 0;" outside of you while loop then add "employeesProcessed++;" directly after "if (choice.equalsIgnoreCase("Y"))" so that each time your program is asked to process an employ you add 1 to your int that is keeping track of how many employees you have processed. Then you can add this variable onto the end of your printed string so it says "Total number of Employees processed: " + employeesProcessed.

How can I put the item order in a different class?

package project;
import java.util.ArrayList;
import java.util.Scanner;
public class project {
public static void main(String[] args) {
// TODO Auto-generated method stub
//Setting up scanner
Scanner input = new Scanner(System.in);
//Variable to allow user to quit input
String quit = "done";
//Constants
double salesTax = 0.11;
double spagPrice = 7;
double ramenPrice = 4;
double pepperPrice = 9;
double steakPrice = 12;
double tunaPrice = 6;
//Constants for loop
double listTime = 1;
double listMax = 10;
//Variable for loop
double itemEntry = 0;
//Keeps running total of item prices
double priceAdd = 0;
//Initializes array lists
ArrayList<String> itemList = new ArrayList<String>();
ArrayList<Integer> priceList = new ArrayList<Integer>();
ArrayList<Integer> buyList = new ArrayList<Integer>();
ArrayList<String> buyitemList = new ArrayList<String>();
//Adds food names to the correct array
itemList.add("Spaghetti Tacos");
itemList.add("Ramen Pizza");
itemList.add("Stuffed Bell Pepper");
itemList.add("Mushroom Steak");
itemList.add("Tuna Suprise");
//Adds prices to the price array
priceList.add(7);
priceList.add(4);
priceList.add(9);
priceList.add(12);
priceList.add(6);
System.out.println("Please enter a number to indicate your desired item.
Type 'done' when you are done or enter up to 10 items.");
System.out.println(" " + "1" + " " + " " + " " + "2" + " " + " " + " " +
"3" + " " + " " + " " + "4" + " " + " " + " " + "5");
System.out.println(itemList);
System.out.println("Prices: " + priceList);
orderEntry (quit, listTime, listMax, priceAdd, buyitemList);
/** while (quit != "done" || listTime <= listMax)
{
System.out.println("Please enter item " + listTime + " :");
itemEntry = input.nextInt();
if (itemEntry == 1){
priceAdd = spagPrice;
buyitemList.add("Spaghetti Tacos");
}
else if (itemEntry == 2){
priceAdd = ramenPrice;
buyitemList.add("Ramen Pizza");
}
else if (itemEntry == 3){
priceAdd = pepperPrice;
buyitemList.add("Stuffed Bell Pepper");
}
else if (itemEntry == 4){
priceAdd = steakPrice;
buyitemList.add("Mushroom Steak");
}
else if (itemEntry == 5){
priceAdd = tunaPrice;
buyitemList.add("Tuna Suprise");
}
else {
priceAdd = 0;
}
buyList.add((int) priceAdd);
listTime += listTime;
}
*/
double amntTacos = 0;
double amntPizza = 0;
double amntPepper = 0;
double amntSteak = 0;
double amntTuna = 0;
double tacoPrice = 0;
double pizzaPrice = 0;
double belPrice = 0;
double mushPrice = 0;
double suprisePrice = 0;
public orderEntry(speTacos)
{
this.orderEntry = amntTacos;
}
public orderEntry(ramPizza)
{
this.orderEntry = amntPizza;
}
public orderEntry(belPepper)
{
this.orderEntry = amntPepper;
}
public orderEntry(musSteak)
{
this.orderEntry = amntSteak;
}
public orderEntry(tunSup)
{
this.orderEntry = amntTuna;
}
tacoPrice = spagPrice * amntTacos;
pizzaPrice = ramenPrice * amntPizza;
belPrice = pepperPrice * amntPepper;
mushPrice = steakPrice * amntSteak;
suprisePrice = tunaPrice * amntTuna;
System.out.println("---------------------");
System.out.println("---------------------");
double subTotal = 0;
double taxAmount = 0;
double totalPrice = 0;
//for (int i : buyList) {
// subTotal = subTotal + i;
//}
subTotal = tacoPrice + pizzaPrice + belPrice + mushPrice + suprisePrice;
taxAmount = subTotal * salesTax;
totalPrice = subTotal + taxAmount;
System.out.println("You have chosen the following items: " +
buyitemList);
System.out.println("---------------------");
System.out.println("Your Subtotal is: $" + subTotal);
System.out.println("Your Tax amount is: $" + taxAmount);
System.out.println("Your Final Total is: $" + totalPrice);
package project;
import java.util.ArrayList;
import java.util.Scanner;
public class orderEntry (String quit, double itemEntry, double spagPrice,
double
ramenPrice, double pepperPrice, double steakPrice, double tunaPrice, double
listTime, double listMax, Scanner input, double priceAdd, ArrayList buyList)
{
Scanner input = new Scanner(System.in);
double speTacos = 0;
double ramPizza = 0;
double belPepper = 0;
double musSteak = 0;
double tunSup = 0;
while (quit != "done" || listTime <= listMax)
{
System.out.println("Please enter item " + listTime + " :");
itemEntry = input.nextInt();
if (itemEntry == 1){
priceAdd = spagPrice;
speTacos = speTacos + 1;
}
else if (itemEntry == 2){
priceAdd = ramenPrice;
ramPizza = ramPizza + 1;
}
else if (itemEntry == 3){
priceAdd = pepperPrice;
belPepper = belPepper + 1;
}
else if (itemEntry == 4){
priceAdd = steakPrice;
musSteak = musSteak + 1;
}
else if (itemEntry == 5){
priceAdd = tunaPrice;
tunSup = tunSup + 1;
}
else {
priceAdd = 0;
}
buyList.add((int) priceAdd);
listTime += listTime;
}
public void getSpagetti(){
return speTacos;
}
public void getRamen(){
return ramPizza;
}
public void getPepper(){
return belPepper;
}
public void getSteak(){
return musSteak;
}
public void getTuna(){
return tunSup;
}
}
OK, trying this now. Still not quite right....
The instructions were:
A class named orderEntry should also be created with the appropriate
constructor, accessor and mutator methods. As the user is entering the
items they wish to order, these items should be placed into a separate
array as they are ordered. Once the user is done entering items, the
program should use the array to output all items that were ordered to
the screen, with their prices.
This is not a solution i would recommend, but for the sake of learning how to use methods:
just put it in another class and call the method from there. Give the methods the parameters needed.
public class whileMethod(String quit, double listTime, double listMax, Scanner input, double priceAdd, ArrayList<String> buyItemList, ) {
while (quit != "done" || listTime <= listMax)
{
System.out.println("Please enter item " + listTime + " :");
itemEntry = input.nextInt();
if (itemEntry == 1){
priceAdd = spagPrice;
buyitemList.add("Spaghetti Tacos");
}
else if (itemEntry == 2){
priceAdd = ramenPrice;
buyitemList.add("Ramen Pizza");
}
else if (itemEntry == 3){
priceAdd = pepperPrice;
buyitemList.add("Stuffed Bell Pepper");
}
else if (itemEntry == 4){
priceAdd = steakPrice;
buyitemList.add("Mushroom Steak");
}
else if (itemEntry == 5){
priceAdd = tunaPrice;
buyitemList.add("Tuna Suprise");
}
else {
priceAdd = 0;
}
buyList.add((int) priceAdd);
listTime += listTime;
}
From here u can call the method in the class:
whileMethod(and all the attributtes needed)

Simple java: error with if statements

So I have been trying to figure this out for the past 5 hours and the reason being...from a beginner point of view this code looks fine with no errors but the output is still wrong...basically for every 10 kids tickets the user gets one free,so the output is fine if the free tickets is less than the adults but it subtracts the extra adults when its the other way around.
package theatre;
import java.util.*;
public class Theatre {
public static void main(String[] args) {
Scanner kybd = new Scanner(System.in);
System.out.println("Enter the number of tickets you would like to buy for each type: ");
System.out.println("Adult: £10.50");
System.out.println("Child: £7.30");
System.out.println("Concessions £8.40");
System.out.println("Adult: ");
int Adult = kybd.nextInt();
System.out.println("Child: ");
int Child = kybd.nextInt();
System.out.println("Concessions: ");
int concessions = kybd.nextInt();
int freeAdult = Child / 10;
if (freeAdult < 9) {
System.out.println("You get " + freeAdult + " adult tickets");
} else {
System.out.println("You don't get any free tickets");
}
System.out.println(freeAdult); //reference out
double adultBill = (Adult * 10.50) - (freeAdult * 10.50);
double childBill = Child * 7.30;
double concessionsBill = concessions * 8.40;
double totalBill = adultBill + childBill + concessionsBill;
double totalBill2 = childBill + concessionsBill;
System.out.println(totalBill2); //reference out
if (freeAdult >= Adult) {
System.out.printf("Total bill is: £%.2f\n", totalBill);
} else if (freeAdult < Adult) {
System.out.printf("Total bill is: £%.2f\n", totalBill2);
} else {
System.out.println("Please enter a corrrect value");
}
}
}
Thanks
I think you have your logic a little confused:
int freeAdult = Child / 10;
if (freeAdult < 9) {
System.out.println("You get " + freeAdult + " adult tickets");
} else {
System.out.println("You don't get any free tickets");
}
appears to be calculating how many free adult tickets the person gets based on the number of child tickets (Child / 10) ...but is then saying they get no tickets if they've qualified for more than 10? I think you might be using the wrong variable here. Then:
double adultBill = (Adult * 10.50) - (freeAdult * 10.50);
double childBill = Child * 7.30;
double concessionsBill = concessions * 8.40;
double totalBill = adultBill + childBill + concessionsBill;
double totalBill2 = childBill + concessionsBill;
System.out.println(totalBill2); //reference out
if (freeAdult >= Adult) {
System.out.printf("Total bill is: £%.2f\n", totalBill);
} else if (freeAdult < Adult) {
System.out.printf("Total bill is: £%.2f\n", totalBill2);
} else {
System.out.println("Please enter a corrrect value");
}
I believe is meant to calculate 2 bills, one including adults and one not and then if the number of free adult tickets is greater than the number of adults, discard the first bill and use the second (which never included the adults calculation), in which case you have your if statement the wrong way around, it should be:
if (freeAdult < Adult) {
System.out.printf("Total bill is: £%.2f\n", totalBill);
} else if (freeAdult >= Adult) {
System.out.printf("Total bill is: £%.2f\n", totalBill2);
...however you should only have to calculate one bill by simply changing the adult calculation to:
double adultBill = freeAdult < Adult ? (Adult * 10.50) - (freeAdult * 10.50) : 0;
Then calculate bill as normal:
double totalBill = adultBill + childBill + concessionsBill;
System.out.printf("Total bill is: £%.2f\n", totalBill);
public class Theatre {
public static void main(String[] args) {
Scanner kybd = new Scanner(System.in);
System.out.println("Enter the number of tickets you would like to buy for each type: ");
System.out.println("Adult: £10.50");
System.out.println("Child: £7.30");
System.out.println("Concessions £8.40");
System.out.println("Adult: ");
int adult = kybd.nextInt();
System.out.println("Child: ");
int child = kybd.nextInt();
System.out.println("Concessions: ");
int concessions = kybd.nextInt();
int freeAdult = child / 10;
System.out.println("You get " + freeAdult + " adult tickets free");
if(adult >0){
adult = adult - freeAdult;
}
double adultBill = (adult * 10.50);
double childBill = child * 7.30;
double concessionsBill = concessions * 8.40;
double totalBill = adultBill + childBill + concessionsBill;
System.out.printf("Total bill is: £%.2f\n", totalBill);
}
}

Unsure about calculating commission based on user input

public static void main(String[] args) {
Scanner keybNum = new Scanner(System.in);
Scanner keybStr = new Scanner(System.in);
boolean yn = false;
//Start of program
System.out.println("Welcome to Currency Exchanger");
System.out.print("Are you an Account Holder (y or n)? ");
String AccHolder = keybStr.next();
boolean blnYN = true;
//validation of y/n answer
while (blnYN) {
if (AccHolder.equalsIgnoreCase("y")) {
yn = true;
blnYN = false;
break;
}//if
else if (AccHolder.equalsIgnoreCase("n")) {
yn = false;
blnYN = false;
break;
}//else if
else {
System.out.println("Invalid value entered. Choose either y/n.");
AccHolder = keybStr.next();
}//else
}//while
//Start of menu choices
System.out.println("Please choose from the following menu.");
System.out.println("\n1: Exchange another currency for Sterling");
System.out.println("2: Buy another currency from us");
System.out.println("0: Exit");
System.out.print("Which option? ");
int MenuChoice = keybNum.nextInt();
//Exchange Variables (First option)
double Euro = 1.37;
double USAD = 1.81;
double JapYen = 190.00;
double Zloty = 5.88;
//Buy Variables (Second Option)
double EuroB = 1.21;
double USADB = 1.61;
double JapYenB = 163.00;
double ZlotyB = 4.89;
//First menu choice screen
if (MenuChoice == 1) {
System.out.println("Currencies to exchange into sterling?");
System.out.println("Euro - EUR");
System.out.println("USA Dollar - USD");
System.out.println("Japanese Yen - JPY");
System.out.println("Polish Zloty - PLN");
System.out.print("Please enter the three letter currency: ");
//Currency input validation
String CurChoice = "";
boolean isCorrectCurrency = false;
do {
CurChoice = keybStr.next();
isCorrectCurrency = CurChoice.matches("^EUR|USD|JPY|PLN$");
if (isCorrectCurrency) {
System.out.println("");
} else {
System.out.print("Invalid Currency Entered. Please Retry: ");
}
} while (!isCorrectCurrency);
//Exchange amount calculator
System.out.print("Enter the amount you wish to exchange of " + CurChoice + ": ");
double ExcAmount = keybStr.nextInt();
double result = 0.00;
//Selection and calculation of user's input
if (CurChoice.equals("EUR")) {
result = ExcAmount / Euro;
DecimalFormat df = new DecimalFormat("#.##");
System.out.println(ExcAmount + " in " + CurChoice + "\t=£" + df.format(result));
} else if (CurChoice.equals("USD")) {
result = ExcAmount / USAD;
DecimalFormat df = new DecimalFormat("#.##");
System.out.println(ExcAmount + " in " + CurChoice + "\t=£" + df.format(result));
} else if (CurChoice.equals("JPY")) {
result = ExcAmount / JapYen;
DecimalFormat df = new DecimalFormat("#.##");
System.out.println(ExcAmount + " in " + CurChoice + "\t=£" + df.format(result));
} else if (CurChoice.equals("PLN")) {
result = ExcAmount / Zloty;
DecimalFormat df = new DecimalFormat("#.##");
System.out.println(ExcAmount + " in " + CurChoice + "\t=£" + df.format(result));
} else {
System.out.println("");
}
Right, this is where I am stuck. So this program is a currency exchange converter. The part I'm unsure about is to calculate the commission. At the start I ask the user if they're an account holder. If they're they don't get charged a commission, whereas if they're then they do. If the amount they wish to exchange is less than £1000 then they get charged a commission of 2%, and if its over £1000 then they get charged a commission of 1%. I wasn't sure how to implement this into my program, so i'm asking you guys to help.
Try this after calculating the result:
double commission = 0.;
if (ExcAmount < 1000) {
commission = result * 0.02;
} else {
commission = result * 0.01;
}
result += commission;
String stringToPrint = "";
if (!yn) { //you could use meaningful variable names
stringToPrint = "Commission = " + commission;
} else {
stringToPrint = "Commission = Not charged";
}
System.out.println(stringToPrint + "\nTotal = " + (result - commission));

Private variable does not return appropriately [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
As the title above states - the problem I've encountered is related to the private variable within the class. The private variable does not return the correct value.
My objective is to retrieve private variable named myIncome from income Class which is a parent to these methods.
But when I try to retrieve myIncome using objIncome.getIncome(); in another class - it returns 0.00 value.
The result should be based on the if statements output.
import java.util.Scanner;
import java.text.DecimalFormat;
public class income {
private double income;
private double myIncome;
Scanner input = new Scanner(System.in);
DecimalFormat df = new DecimalFormat("###.##");
public void summery1(double myIncome, double income, double tax, double nic, double personalTAXAllowance, double personalNICAllowance,double taxed, double niced){
this.myIncome = myIncome;
System.out.println("Your income before tax: " + income);
System.out.println("Personal allowance: " + personalTAXAllowance);
System.out.println("NIC allowance: " + personalNICAllowance);
System.out.println("Tax rate: " + tax + " %");
System.out.println("National insurance rate: " + nic + " %");
System.out.println("Your annual income after tax: " + df.format(myIncome));
System.out.println("Your income on monthly basis: " + df.format(myIncome / 12) + "\n");
}
public void summery2(double myIncome, double income, double tax, double nic, double personalTAXAllowance, double personalNICAllowance,double taxed, double niced, double additionalNIC, double resault){
this.myIncome = myIncome;
System.out.println("Your income before tax: " + income);
System.out.println("Personal allowance: " + personalTAXAllowance);
System.out.println("NIC allowance: " + personalNICAllowance);
System.out.println("Tax rate: " + tax + " %");
System.out.println("National insurance rate: " + nic + " %");
System.out.println("Your annual income after tax: " + df.format(myIncome));
System.out.println("Your income on monthly basis: " + df.format(myIncome / 12) + "\n");
}
public void clcSalary(){
System.out.println("Please enter your annual salary before tax");
double income = input.nextDouble();
if (income <= 32010){
double tax = 0.20;
double nic = 0.12;
double personalTAXAllowance = 9440;
double personalNICAllowance = 7748;
double taxed = (income - personalTAXAllowance) * tax;
double niced = (income - personalNICAllowance) * nic;
myIncome = income - (taxed + niced);
summery1(myIncome, income, tax, nic, personalTAXAllowance,personalNICAllowance,taxed,niced);
}
else if (income > 32010 && income < 150000 ){
double tax = 0.40;
double nic = 0.12;
double personalTAXAllowance = 9440;
double personalNICAllowance = 7748;
double taxed = (income - personalTAXAllowance) * tax;
double niced = (income - personalNICAllowance) * nic;
if (income > 41444){
double additionalNIC = income - 41444;
double resault = additionalNIC * 0.02;
this.myIncome = income - (taxed + niced) + resault;
summery2(myIncome, income, tax, nic, personalTAXAllowance,personalNICAllowance,taxed,niced,additionalNIC, resault);
}
else{
this.myIncome = income - (taxed + niced);
summery1(myIncome,income, tax, nic, personalTAXAllowance,personalNICAllowance,taxed,niced);
}
}
else{
double tax = 0.45;
double nic = 0.12;
double personalTAXAllowance = 9440;
double personalNICAllowance = 7748;
double taxed = (income - personalTAXAllowance) * tax;
double niced = (income - personalNICAllowance) * nic;
if (income > 41444){
double additionalNIC = income - 41444;
double resault = additionalNIC * 0.02;
this.myIncome = income - (taxed + niced) + resault;
summery2(myIncome, income, tax, nic, personalTAXAllowance,personalNICAllowance,taxed,niced,additionalNIC, resault);
}
else{
this.myIncome = income - (taxed + niced);
summery1(myIncome, income, tax, nic, personalTAXAllowance,personalNICAllowance,taxed,niced);
}
}
}
public void clcHourlyRate(double income){
System.out.println("Please enter your hourly rate: \n");
double hourlyRate = input.nextDouble();
System.out.println("Please enter the hours you've worked this week \n");
double hoursWeek = input.nextDouble();
income = ((hourlyRate * hoursWeek) * 4) * 12;
if (income <= 32010){
double tax = 0.20;
double nic = 0.12;
double personalTAXAllowance = 9440;
double personalNICAllowance = 7748;
double taxed = (income - personalTAXAllowance) * tax;
double niced = (income - personalNICAllowance) * nic;
this.myIncome = income - (taxed + niced) / 12;
summery1(myIncome, income, tax, nic, personalTAXAllowance,personalNICAllowance,taxed,niced);
}
else if (income > 32010 && income <= 150000 ){
double tax = 0.40;
double nic = 0.12;
double personalTAXAllowance = 9440;
double personalNICAllowance = 7748;
double taxed = (income - personalTAXAllowance) * tax;
double niced = (income - personalNICAllowance) * nic;
if (income > 41444){
double additionalNIC = income - 41444;
double resault = additionalNIC * 0.02;
this.myIncome = ((income - (taxed + niced)) / 12) + resault;
summery2(myIncome, income, tax, nic, personalTAXAllowance,personalNICAllowance,taxed,niced,additionalNIC, resault);
}
else{
myIncome = (income - (taxed + niced)) / 12;
myIncome = income - (taxed + niced) / 12;
summery1(myIncome, income, tax, nic, personalTAXAllowance,personalNICAllowance,taxed,niced);
}
}
else{
double tax = 0.45;
double nic = 0.12;
double personalTAXAllowance = 9440;
double personalNICAllowance = 7748;
double taxed = (income - personalTAXAllowance) * tax;
double niced = (income - personalNICAllowance) * nic;
if (income > 41444){
double additionalNIC = income - 41444;
double resault = additionalNIC * 0.02;
this.myIncome = ((income - (taxed + niced)) / 12) + resault;
summery2(myIncome, income, tax, nic, personalTAXAllowance,personalNICAllowance,taxed,niced,additionalNIC, resault);
}
else{
this.myIncome = (income - (taxed + niced)) / 12;
summery1(myIncome, income, tax, nic, personalTAXAllowance,personalNICAllowance,taxed,niced);
}
}
}
public double getIncome(){
return myIncome;
}
}
Here is the entire code of the whole class.
public class savings {
private double v_sav;
private DecimalFormat df = new DecimalFormat("###.##");
private Scanner input = new Scanner(System.in);
private income myincome = new income();
public void setSavings() {
double income = myincome.getIncome();
System.out.println(income);
System.out.println("Please enter the amount of months: ");
int months = input.nextInt();
df.format(v_sav = income * months);
System.out.println("Your savings in " + months + " months"+ "will be: "+ v_sav);
}
public double getSavings() {
return v_sav;
}
}
This is the class which uses the getIncome method from Class Income object.
public class PFA {
public static void main(String[] args) {
int option;
do{
mainMenu();
option = input.nextInt();
if (option > 5){
System.out.println("Please enter a value between 1 and 5");
}
else{
if (option == 1){
menuIncome(v_income);
}
else if (option == 2){
menuExpenses(n_expenses, c_expenses, v_choice, v_exit);
}
else if (option == 3){
savings mySavings = new savings();
mySavings.setSavings();
System.out.println(mySavings.getSavings());
}
}
}while (option != 5);
Main method.
I'm assuming you have a driver like (which is what you have in your 3rd else-if)
public static void main(String[] args) {
savings s = new savings();
s.setSavings();
double value = s.getSavings();
}
In this case, of course it's going to be 0.0 with the line
double income = myincome.getIncome();
in setSavings(), you haven't called the methods that change the value of myIncome.
In your savings class,
private income myincome = new income();
creates a new income instance, which, because you don't have a constructor, initializes the value of the instance field myIncome to 0. That is the value you are getting back with getIncome().
You aren't calling clcSalary() anywhere. You should do that before calling getIncome().
Are the summery functions being printed? What is the value of myIncome there?
In other words, if getIncome is being called before either clcSalary or clcHourlyRate then your variable will remain 0.

Categories