This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
So I have a school assignment to do in Java, I have created the program but it does not give me an output. Im still a beginner so plz help me fix the problem. the first half of my code uses joptionpane but i want to display the output in the console. this is my code:
import java.util.Scanner;
import javax.swing.JOptionPane;
public class payroll2
{
public static void main(String args[])
{
new payroll2().SetPayrollDetail();
new payroll2().SetBonus();
new payroll2().SetCommission();
new payroll2().SetNssf();
new payroll2().SetNetSalary();
new payroll2().GetPayroll();
}
Scanner myScanner=new Scanner(System.in);
Double empID;
String empName;
String empDept;
String designation;
Double basicSalary;
Double bonus;
Double commission;
Double nssf;
Double netSalary;
public void SetPayrollDetail()
{
empID = Double.parseDouble(JOptionPane.showInputDialog(null, "Enter ID: ", "ID",JOptionPane.QUESTION_MESSAGE));
empName = JOptionPane.showInputDialog(null, "Enter Name: ", "Name",JOptionPane.QUESTION_MESSAGE);
empDept = JOptionPane.showInputDialog(null, "Enter Department (Marketing or Other): ", "Department",JOptionPane.QUESTION_MESSAGE);
designation = JOptionPane.showInputDialog(null, "Enter Designation (Manager, Executive or Other): ", "Designation",JOptionPane.QUESTION_MESSAGE);
basicSalary = Double.parseDouble(JOptionPane.showInputDialog(null, "Enter Basic Salary: ", "Basic Salary",JOptionPane.QUESTION_MESSAGE));
}
public void SetBonus()
{
if(basicSalary < 1500){
bonus = 0.0;
}
else if(basicSalary>=1500 && basicSalary<3000){
bonus = basicSalary * (12/100);
}
else if(basicSalary>=3000 && basicSalary<5000){
bonus = basicSalary * (15/100);
}
else{
bonus = basicSalary * (25/100);
}
System.out.println(bonus);
}
public void SetCommission()
{
if( empDept.equalsIgnoreCase("other") ){
commission = 0.0;
}
else if( empDept.equalsIgnoreCase("marketing") && designation.equalsIgnoreCase("manager") ){
commission = basicSalary * (30/100);
}
else if( empDept.equalsIgnoreCase("marketing") && designation.equalsIgnoreCase("executive") ){
commission = basicSalary * (15/100);
}
else if( empDept.equalsIgnoreCase("marketing") && designation.equalsIgnoreCase("other") ){
commission = basicSalary * (10/100);
}
else{
commission = 0.0;
}
System.out.println(commission);
}
public void SetNssf()
{
if(basicSalary < 1500){
nssf = basicSalary * (5/100);
}
else if(basicSalary>=1500 && basicSalary<3000){
nssf = basicSalary * (8/100);
}
else if(basicSalary>=3000 && basicSalary<5000){
nssf = basicSalary * (12/100);
}
else if(basicSalary>=5000 && basicSalary<7000){
nssf = basicSalary * (15/100);
}
else if(basicSalary>=7000 && basicSalary<10000){
nssf = basicSalary * (20/100);
}
else{
nssf = basicSalary * (25/100);
}
System.out.println(nssf);
}
public void SetNetSalary()
{
netSalary = ( basicSalary + commission + bonus ) - nssf;
System.out.println(netSalary);
}
public void GetPayroll()
{
System.out.println("Payroll Details \n _____________________");
System.out.println("ID:\t" + empID);
System.out.println("name:\t" + empName);
System.out.println(bonus);
System.out.println(commission);
System.out.println(nssf);
System.out.println(netSalary);
}
}
You have a bunch of values which aren't initialized to anything by default:
Double empID;
String empName;
String empDept;
// etc.
When you create an instance of the object, you call a method to initialize them:
new payroll2().SetPayrollDetail();
But then you don't keep that instance. You immediately create an entirely new instance and try to operate on it:
new payroll2().SetBonus();
This new instance never had its values initialized to anything. So it can't use those values. Instead, you want to keep that original instance so you can operate on that:
payroll2 instance = new payroll2();
instance.SetPayrollDetail();
instance.SetBonus();
// etc.
You are recreating your instance of payroll2 every time you make an operation. Use a single instance.
payroll2 p = new payroll2();
p.SetPayrollDetail();
p.SetBonus();
p.SetCommission();
p.SetNssf();
p.SetNetSalary();
p.GetPayroll();
Moreover, method should begin with a tiny letter, class name with a capital one.
Related
I want to start by saying that I'm a newby in Java, and it's also my first time asking something on this site. After 3 days trying to figure out how to break this small program in methods, I haven't been able to do so. could anyone help me with it ?
I've been reading and it looks like I'm violating the single responsibility principle. Any opinions would be more than welcome.
public class RateSystem {
double employeeSalary;
public int salaryRate(String employeePosition) {
if (employeePosition.equalsIgnoreCase("1")) {
return 40;
} else if (employeePosition.equalsIgnoreCase("2")) {
return 30;
} else
employeePosition.equalsIgnoreCase("3");
return 50;
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Employee position please...");
System.out.println("Press 1 for IT " + "\n" + "Press 2 for Tech" +
"\n" + "Press 3 for engineer");
String ePosition = input.nextLine();
RateSystem raul = new RateSystem();
int getPay = raul.salaryRate(ePosition);
System.out.println("How many hours did he work for the week?...");
int weekHours = input.nextInt();
int totalPay = 0;
if (weekHours <= 40) {
totalPay = getPay * weekHours;
System.out.println("Employee salary is " + totalPay);
} else {
int overTimeHours = weekHours - 40;
int extra$$PerOverTime = overTimeHours * getPay +(overTimeHours * getPay/2);
totalPay = getPay * (weekHours - overTimeHours);
System.out.println("The employee accumulated 40 hours equivalent to $"+
totalPay + " plus $" + extra$$PerOverTime + " overtime hours, a total of $"+(extra$$PerOverTime + totalPay));
}
}
}
If we are looking at main(), It does multiple tasks:
Receive user input
Calculate total pay and possible other finance information
Print the results
How's that for starters
I see followings could be added.
1) Salaries are created for Employees so why don't you create and Employee class and encapsulate details inside it like "employeePosition". So you can add more things later and having setters inside it you will get the chance of changing setter logics for employees.
2) You can create a Calculator class and create methods accepting single Employee or a List of Employees and calculate their Salary Rates.
3) You also can add a Printing related class. So you can produce different printing for single or List of Employees or may be like a tabular format.
I have identified following methods in your code.
1) showMainMenu --> responsible to show menu to the user
2) readMenuSelection --> here you will read whatever user has selected in the main menu. It should be read in int value rather than string.
3) For each Selection from menu there will be separate methods such as payForIT(), payForTech() and payForEngineer()
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Employee position please...");
System.out.println("Press 1 for IT " + "\n" + "Press 2 for Tech" + "\n" + "Press 3 for engineer");
String position = input.nextLine();
RateSystem rateSystem = new RateSystem();
rateSystem.setEmployeePosition(position);
System.out.println("How many hours did he work for the week?...");
int weekHours = input.nextInt();
rateSystem.setWeekHours(weekHours);
rateSystem.calculateSalary();
int totalPay = rateSystem.getTotalPay();
int overTime = rateSystem.getOvertime();
if (overTime > 0) {
System.out.println("The employee accumulated 40 hours equivalent to $" + totalPay + " plus $" + overTime
+ " overtime hours, a total of $" + (overTime + totalPay));
} else {
System.out.println("Employee salary is " + totalPay);
}
}
}
public class RateSystem {
private final int STANDARD_WORK = 40;
private double employeeSalary;
private int weekHours;
private Position employeePosition;
private int totalPay = 0;
private int overTime = 0;
public void setEmployeePosition(String position) {
employeePosition = Position.fromString(position);
}
public void setWeekHours(int weekHours) {
this.weekHours = weekHours;
}
public int getTotalPay() {
return totalPay;
}
public int getOvertime() {
return overTime;
}
public void calculateSalary() {
int salaryRate = employeePosition.getRate();
int workhours = (weekHours > STANDARD_WORK) ? STANDARD_WORK : weekHours;
int overTimeHours = (weekHours > STANDARD_WORK) ? (weekHours - STANDARD_WORK) : 0;
totalPay = workhours * weekHours;
overTime = (overTimeHours * salaryRate) + (overTimeHours * salaryRate / 2);
}
}
public enum Position {
IT(40), Tech(30), Engineer(50);
private int rate = 0;
Position(int r) {
rate = r;
}
public int getRate() {
return rate;
}
public static Position fromString(String position) {
switch (position) {
case "1":
return IT;
case "2":
return Tech;
case "3":
return Engineer;
}
return null;
}
}
To follow single responsibility principle you have to create method for each common task in your program. That helps do not repeat code and helps to modify code in one place.
I have created separate methods for building string and for printing string as you use it frequently in your code:
package com.stackoverflow.main;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
println("Employee position please...");
println(buildString("Press 1 for IT ", "\n", "Press 2 for Tech", "\n", "Press 3 for engineer"));
String ePosition = input.nextLine();
RateSystem raul = new RateSystem();
int getPay = raul.salaryRate(ePosition);
println("How many hours did he work for the week?...");
int weekHours = input.nextInt();
int totalPay = 0;
if (weekHours <= 40) {
totalPay = getPay * weekHours;
println(buildString("Employee salary is ", String.valueOf(totalPay)));
} else {
int overTimeHours = weekHours - 40;
int extra$$PerOverTime = overTimeHours * getPay + (overTimeHours * getPay / 2);
totalPay = getPay * (weekHours - overTimeHours);
println(buildString("The employee accumulated 40 hours equivalent to $", String.valueOf(totalPay),
" plus $", String.valueOf(extra$$PerOverTime), " overtime hours, a total of $",
String.valueOf((extra$$PerOverTime + totalPay))));
}
}
private static String buildString(String... strings) {
StringBuilder builder = new StringBuilder();
for (String string : strings) {
builder.append(string);
}
return builder.toString();
}
private static void println(String s) {
System.out.println(s);
}
}
And class RateSystem:
package com.stackoverflow.main;
public class RateSystem {
double employeeSalary;
public int salaryRate(String employeePosition) {
if (equalsIgnoreCase(employeePosition, "1")) {
return 40;
} else if (equalsIgnoreCase(employeePosition, "2")) {
return 30;
} else if (equalsIgnoreCase(employeePosition, "3"))
return 50;
return 0;
}
private boolean equalsIgnoreCase(String arg1, String arg2) {
return arg1.equalsIgnoreCase(arg2);
}
}
I'm sure this has a simple solution, but I'm new to Java and can't work it out.
I have a subclass Payroll that extends a superclass Pay, it contains an overridden method called 'calc_payroll'. From this method, I want to call the superclass method of the same name, and assign the output to a variable in the overriding method. My code is below
public class Payroll extends Pay
{
public double calc_Payroll()
{
double grossPay = super.calc_Payroll();
double taxAmt = tax(grossPay);
double netPay = grossPay - taxAmt;
System.out.println(grossPay);
return netPay;
}
}
Below is the code from the calc_payroll method in the superclass
public double calc_Payroll()
{
double otRate = rate * 1.77;
double otHours = ttlHours - stHours;
if(stHours == 0)
{
grossPay = otHours * rate;
}
else
{
grossPay = ((stHours * rate) + (otHours * otRate));
}
System.out.println(stHours + "//" + otHours + "//" + rate);//for testing
return grossPay;
}
the superclass method functions without issue to calculate and return the gross pay when called from a different subclass, but when calling it from a method with the same name, the print line in the code above (that I have labelled for testing) displays zero's for all variables
Code for full 'Pay' class is below as requested
public class Pay
{
private double ttlHours;
private int stHours;
private double rate;
double grossPay = 0.0;
final double TAXL = 0.07;
final double TAXM = 0.1;
final double TAXH = 0.16;
public void SetHours(double a)
{
ttlHours = a;
}
public void SetHoursStr(int a)
{
stHours = a;
}
public void SetRate(double a)
{
rate = a;
}
public double GetHours()
{
return ttlHours;
}
public int GetStHours()
{
return stHours;
}
public double GetRate()
{
return rate;
}
public double taxRate()
{
double taxRate = 0.0;
if(grossPay <= 399.99)
{
taxRate = TAXL;
}
else if(grossPay <= 899.99)
{
taxRate = TAXM;
}
else
{
taxRate = TAXH;
}
return taxRate;
}
public double tax(double grossPay)
{
double ttlTax = 0.0;
if(grossPay < 400.00)
{
ttlTax += (grossPay * TAXL);
}
else if(grossPay < 900.00)
{
ttlTax += (grossPay * TAXM);
}
else
{
ttlTax += (grossPay * TAXH);
}
return ttlTax;
}
public double calc_Payroll()
{
double otRate = rate * 1.77;
double otHours = ttlHours - stHours;
if(stHours == 0)
{
grossPay = otHours * rate;
}
else
{
grossPay = ((stHours * rate) + (otHours * otRate));
}
System.out.println(stHours + "//" + otHours + "//" + rate);//for testing
return grossPay;
}
}
The subclass Payroll contains no other code
Below is the code that accepts user input to assign values to the initialized variables
public class CalPayroll extends Pay
{
Payroll nPay = new Payroll();
Accept Read = new Accept();
public void AcceptPay()
{
char select = '0';
while(select != 'e' && select != 'E')
{
System.out.println("Payroll Computation \n");
System.out.print("Enter number of hours worked (00.0) <0 for Quick exit>: ");
SetHours(Read.AcceptInputDouble());
System.out.print("Enter first number of hours straight (integer or 0 to disable): ");
SetHoursStr(Read.AcceptInputInt());
System.out.print("Enter hourly rate of worker (00.00): ");
SetRate(Read.AcceptInputDouble());
Screen.ScrollScreen('=', 66, 1);
Screen.ScrollScreen(1);
displayInfo();
System.out.println("e to exit, any other letter + <Enter> to continue");
select = Read.AcceptInputChar();
}
}
public void displayInfo()
{
NumberFormat currency = NumberFormat.getCurrencyInstance();
NumberFormat percent = NumberFormat.getPercentInstance();
System.out.println("Gross pay is :" + currency.format(calc_Payroll()));
System.out.println("Tax is :" + percent.format(taxRate()));
System.out.println("Net pay is :" + currency.format(nPay.calc_Payroll()));
Screen.ScrollScreen(1);
}
}
I'm confused!
Its clear from you code that ttlHours, stHours and rate are not initialised with some reasonable value. So when you just call super.calc_Payroll(), values like 0 or 0.0 are used as i explained in my comment. Its good to first set values of these variables before calling super.calc_Payroll().
SetHours(23.4); //some value
SetHoursStr(5); //some value
SetRate(2.3); //some value
Also you don't have constructor for Pay class, try making it and initialising all uninitialised variable in constructor or use setter/getter methods to set and get values.
Since your both classes extends Pay class, it creates the problem which you are facing. When you call SetHours(Read.AcceptInputDouble()), it set the variable inherited by CalPayroll from Pay, not the variables inherited by Payroll class. What you have to do is to set variables for Payroll instance as well as for current class as both extends Pay. Do the following replace your while loop as,
while(select != 'e' && select != 'E')
{
System.out.println("Payroll Computation \n");
System.out.print("Enter number of hours worked (00.0) <0 for Quick exit>: ");
SetHours(Read.AcceptInputDouble());
nPay.SetHours(GetHours());
System.out.print("Enter first number of hours straight (integer or 0 to disable): ");
SetHoursStr(Read.AcceptInputInt());
nPay.SetHoursStr(GetStHours());
System.out.print("Enter hourly rate of worker (00.00): ");
SetRate(Read.AcceptInputDouble());
nPay.SetRate(GetRate());
Screen.ScrollScreen('=', 66, 1);
Screen.ScrollScreen(1);
displayInfo();
System.out.println("e to exit, any other letter + <Enter> to continue");
select = Read.AcceptInputChar();
}
Please post the complete code.
It seems that for some reason your variables of super class method not getting assigned values properly. And they are initialized with their default values which is making everything 0. I'll be able to help better if you paste the complete class.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
Hi all I'm trying to loop through an array using a password of 4 letters and an ID of 4 int numbers.
Thus far I can create the two 'keys' BUT I can't get them to search for the account on the arraylist I have despite it's creation. I really don't know how to fix this problem since the only way seems to be to just call for an 'If' statement or switch.
Here is where I have the code set up:
int acctID;
int depositingAmount;
//System.out.println("Input your ID and then your password to deposit money.");
String inputID = JOptionPane.showInputDialog("Please input your ID to begin depositing money.");
acctID = Integer.parseInt(inputID);
String inputPassword = JOptionPane.showInputDialog("Please input your password to verify your account.");
// int depositAmount;
// do {
for (int i = 0; i < bankAccounts.size(); i++)//Loops through accounts in my arraylist.
{
if (acctID == bankAccounts.get(i).getAccountId() && inputPassword == bankAccounts.get(i).getPassword())//If ID and password work are true then it goes in here.
{
String depositAmount = JOptionPane.showInputDialog("Please input how much money you want to "
+ "input");//An here is where you would be able to spit out how much money to deposit.
depositingAmount = Integer.parseInt(depositAmount);
bankAccounts.get(i).deposit(depositingAmount);
break;
}
}
Like you can see the loop in theory is suppose to go "Oh okay lets me start going though all of the accounts in the list until I get to yours" and when it finds it "oh hey I found your account, here let me give you the deposit feature". Sorry if I tried to simplify it too much in this paragraph its just that this problem is frustrating me too no end because I know that if I can solve this then the rest of my project is done. I have a withdraw feature also but that's basically the same thing but playing with different methods on the same class.
EDIT: Here are the constructors
public BankAccount() {//ADDED TWO PARAMETERS
//NO ARGUMENT CONSTRUCTOR
accountId = (int) (Math.random() * 9000) + 999;
//RANDBETWEEN
setAccountBalance(0);
Random passcode = new Random();
//char charcs = (char)(passcode.nextInt(26) + 'a');
//Added string.
String chars = "abcdefghijklmnopqrstuvwxyz";
int length = chars.length();
for (int i = 0; i < 4; i ++){
password += chars.split("")[ (int) (Math.random() * (length - 1)) ];}
}
public BankAccount(double accountBalance) { // ONE ARGUMENT CONSTRUCTOR
accountId = (int) (Math.random() * 9000) + 1000;
setAccountBalance(accountBalance);
//Random passcode = new Random();
//password = (String) (passcode.nextInt(26)) + 'a';
//NEED A VARIABLE TO PASS IN
//4 Digit password
String chars = "abcdefghijklmnopqrstuvwxyz";
int length = chars.length();
for (int i = 0; i < 4; i ++){
password += chars.split("")[ (int) (Math.random() * (length - 1)) ];}
}
An here are the getters..
public int getAccountId() {
return accountId;
}
public String getPassword() {
return password;
}
Also here are the fields I created..
private int accountId;
private double accountBalance;
private static double annualInterestRate = 0.045;
private static java.util.Date dateCreated = new java.util.Date();
private String name;
private String password = "";
Here is where I stand with the If statement
if (acctID == bankAccounts.get(i).getAccountId() && inputPassword.equals(bankAccounts.get(i).getPassword()))
I've seen the other thread that's been posted has a similar question but their answer of just putting .equals() is not enough. Unless i'm stuppose to just take out bankAccounts from the line.
EDIT 2: The entire code.
import java.util.Random;
public class BankAccount {
private int accountId;
private double accountBalance;
private static double annualInterestRate = 0.045;
private static java.util.Date dateCreated = new java.util.Date();
private String name;
private String password = "";
public BankAccount() {//ADDED TWO PARAMETERS
//NO ARGUMENT CONSTRUCTOR
accountId = (int) (Math.random() * 9000) + 999;
//RANDBETWEEN
setAccountBalance(0);
Random passcode = new Random();
//char charcs = (char)(passcode.nextInt(26) + 'a');
//Added string.
String chars = "abcdefghijklmnopqrstuvwxyz";
int length = chars.length();
for (int i = 0; i < 4; i ++){
password += chars.split("")[ (int) (Math.random() * (length - 1)) ];}
}
public BankAccount(double accountBalance) { // ONE ARGUMENT CONSTRUCTOR
accountId = (int) (Math.random() * 9000) + 1000;
setAccountBalance(accountBalance);
//Random passcode = new Random();
//password = (String) (passcode.nextInt(26)) + 'a';
//NEED A VARIABLE TO PASS IN
//4 Digit password
String chars = "abcdefghijklmnopqrstuvwxyz";
int length = chars.length();
for (int i = 0; i < 4; i ++){
password += chars.split("")[ (int) (Math.random() * (length - 1)) ];}
}
public int getAccountId() {
return accountId;
}
public double getAccountBalance() {
return accountBalance;
}
public void setAccountBalance(double accountBalance) {
this.accountBalance = accountBalance;
}
public double getAnnualInterestRate() {
return annualInterestRate;
}
public void setAnnualInterestRate(double annualInterestRate) {
this.annualInterestRate = annualInterestRate;
}
public void withdraw(double amountToWithdraw) {
if (amountToWithdraw > accountBalance) {
//putting together withdraw make sure to have a validation to stop ppl from going over.
System.out.println("Sorry you cannot exceed the amount you have in your balance.");
}
else {
accountBalance = accountBalance - amountToWithdraw;
}
}
public void deposit(double amountToDeposit) {
if (amountToDeposit < 0) {
//deposits cannot be negative
System.out.println("You cannot deposit a negative amount of dallars.");
}
else {
accountBalance = accountBalance + amountToDeposit;
}
}
public double getMonthlyInterestRate() {
int MonthsInAYear = 12;//method variable is small BUT just need to get results
double monthlyInterestRate = annualInterestRate / MonthsInAYear;
return monthlyInterestRate;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String toString(){
String bankInfo = " Password: " + getPassword() + " Account ID: " + getAccountId();
return bankInfo;
}
}
public class CurrentAccount extends BankAccount{
private static float overdraftLimit = 100;
CurrentAccount(){
super();
}
public static float getOverdraftLimit() {
return overdraftLimit;
}
// MAKE A SETTER FOR THE OVERDRAFTLIMIT
public void withdraw(double amountToWithdraw){
if (amountToWithdraw <= getAccountBalance()+overdraftLimit) {
setAccountBalance(getAccountBalance() - amountToWithdraw);
}
else {
System.out.println("Error this transaction has been cancelled.");
}
}
}
public class SavingsAccount extends BankAccount{
private static double interest;
public SavingsAccount (){
super();
interest = 0;
}
public void addInterest(){
interest = getAccountBalance() * getMonthlyInterestRate(); //GETTING ZEROS FROM ACCOUNTBALANCE
//CHANGE getAccountBalance with some other initial payment.
super.deposit(interest);
}
public double getInterest() {
return interest;
}
public void setInterest(float interest) {
this.interest = interest;
}
}
public class Bank {
Scanner input = new Scanner(System.in);
Scanner Restart = new Scanner(System.in);
private static ArrayList<BankAccount> bankAccounts; // MADE THIS STATIC
public Bank() {
bankAccounts = new ArrayList<BankAccount>();
}
public void openAccount() {
Object[] possibilities = {"Regular Account", "Savings Account", "Checking Account"};
Object inputValue = JOptionPane.showInputDialog(null, "Please pick an option from this menu: ",
"input", JOptionPane.INFORMATION_MESSAGE, null, possibilities, possibilities [0]);
if (inputValue.equals("Regular Account")) {
// Make a regular acct
String inputName = JOptionPane.showInputDialog(null, "Please input your name");
BankAccount newBankAccount = new BankAccount();
newBankAccount.setName(inputName);
bankAccounts.add(newBankAccount);
JOptionPane.showMessageDialog(null, "Account ID: " + newBankAccount.getAccountId());
JOptionPane.showMessageDialog(null, "Account Password: " + newBankAccount.getPassword());
} else if (inputValue.equals("Savings Account")) {
// Make a savings acct
String inputNameSavings = JOptionPane.showInputDialog(null, "Please input your name");
BankAccount newBankAccount = new SavingsAccount();
newBankAccount.setName(inputNameSavings);
bankAccounts.add(newBankAccount);
JOptionPane.showMessageDialog(null, "Account ID: " + newBankAccount.getAccountId());
JOptionPane.showMessageDialog(null, "Account Password: " + newBankAccount.getPassword());
} else if (inputValue.equals("Checking Account")) {
// Make a checking acct
String inputNameChecking = JOptionPane.showInputDialog(null, "Please input your name");
BankAccount newBankAccount = new CurrentAccount();
newBankAccount.setName(inputNameChecking);
bankAccounts.add(newBankAccount);
JOptionPane.showMessageDialog(null, "Account ID: " + newBankAccount.getAccountId());
JOptionPane.showMessageDialog(null, "Account Password: " + newBankAccount.getPassword());
}
}
public static ArrayList<BankAccount> getBankAccounts() {
return bankAccounts;//Moving this into the Open.Account?
}
public void closeAccount() {
System.out.println("Hello give me the name of the" + " "
+ "account you would like to close.");
String userName = input.next();// Gets input for first choice.
// Ask for account id
System.out.println("Please input your account ID");
int userAccountId = input.nextInt();
for (int i = 0; i < bankAccounts.size(); i++) {
if (bankAccounts.get(i).getName().equals(userName)
&& bankAccounts.get(i).getAccountId() == userAccountId) {
bankAccounts.remove(i);
System.out.println("Account removed");
}
}
// anyway, you would set the name probably in the constructor function
// for that particular instantiation of the class
}
public void update() {
// UPDATES MY ACCOUNTS
for (int i = 0; i < bankAccounts.size(); i++) {
if (bankAccounts.get(i) instanceof SavingsAccount) {
((SavingsAccount) bankAccounts.get(i)).addInterest();
} else if (bankAccounts.get(i) instanceof CurrentAccount) {
if (bankAccounts.get(i).getAccountBalance() < 0) {
System.out.println("\nThe Account: " + bankAccounts.get(i).getName() + " has been OverDrafted.\n");
}
}
}
}// ends update
public void withdraw(){
System.out.println("Input your ID and then your password to withdraw money.");
int acctID = input.nextInt();
int withdrawAmount;
// do {
for (int i = 0; i < bankAccounts.size(); i++){
//input needed.
if (acctID == bankAccounts.get(i).getAccountId()){
System.out.println("We have found your account. Please input how much money you would like to withdraw.");
withdrawAmount = input.nextInt();
bankAccounts.get(i).withdraw(withdrawAmount);
break;
}
// } while (input != 1);
}
}
public void deposit(){
int acctID;
int depositingAmount;
//System.out.println("Input your ID and then your password to deposit money.");
String inputID = JOptionPane.showInputDialog("Please input your ID to begin depositing money.");
acctID = Integer.parseInt(inputID);
String inputPassword = JOptionPane.showInputDialog("Please input your password to verify your account.");
// int depositAmount;
// do {
for (int i = 0; i < bankAccounts.size(); i++)//Loops through accounts in my arraylist.
{
if (acctID == bankAccounts.get(i).getAccountId() && inputPassword.equals(bankAccounts.get(i).getPassword()))//If ID and password work are true then it goes in here.
{
String depositAmount = JOptionPane.showInputDialog("Please input how much money you want to "
+ "input");//An here is where you would be able to spit out how much money to deposit.
depositingAmount = Integer.parseInt(depositAmount);
bankAccounts.get(i).deposit(depositingAmount);
break;
}
}
}
}
An finally the class i'm running it on...
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class TestBankAccount {
public static void main(String[] args) {
// JOptionPane.showMessageDialog(null, "Hello User.");
Object[] menuPossibilities = {"Create a New Account", "Deposit", "Withdraw", "Display Balance", "Exit"};
Object menuValues = JOptionPane.showInputDialog(null, "Please pick an option from this menu: ",
"input", JOptionPane.INFORMATION_MESSAGE, null, menuPossibilities, menuPossibilities [0]);
while (!menuValues.equals("Exit")){
Bank newBank = new Bank();
// Bank newBank1 = new Bank();
// Bank newBank2 = new Bank(); Do the same thing as below but switch out
// bank1 and bank2 as a substitute.
ArrayList<BankAccount> bankList = newBank.getBankAccounts();
if (menuValues.equals("Create a New Account")){
newBank.openAccount();
}
else if (menuValues.equals("Deposit")){
newBank.deposit();
}
else if (menuValues.equals("Withdraw")){
newBank.withdraw();
}
else if (menuValues.equals("Display Balace")){
newBank.deposit();
}
else if (menuValues.equals("Exit")){
System.out.println("Thank you for using our service.");
}
menuValues = JOptionPane.showInputDialog(null, "Since you did not pick 5 please pick another option: ",
"input", JOptionPane.INFORMATION_MESSAGE, null, menuPossibilities, menuPossibilities [0]);
}
}
}
Use .equals method to check strings for equality.
i have 2 java programs , the first one takes all information about the employee(id , name , department etc)from the user and prints it , the second program lets the user choose how many number of employees are there then it takes the values like(employ id, name etc), this program uses an array to store the values , it should print all values of different employees , but when i run the program the second set of values overrides the first set of values and prints the second set of values twice , im a beginner so plse help
This is the first program
import java.util.Scanner;
public class payroll2
{
public static void main(String args[])
{
payroll2 payroll = new payroll2();
payroll.SetPayrollDetail();
payroll.SetBonus();
payroll.SetCommission();
payroll.SetNssf();
payroll.SetNetSalary();
payroll.GetPayroll();
}
Scanner myScanner=new Scanner(System.in);
int empID;
String empName;
String empDept;
String designation;
int basicSalary;
double bonus;
double commission;
double nssf;
double netSalary;
public void SetPayrollDetail()
{
System.out.println("Enter ID: ");
empID = myScanner.nextInt();
System.out.println("Enter Name: ");
empName = myScanner.next();
System.out.println("Enter Department (Marketing or Other): ");
empDept = myScanner.next();
System.out.println("Enter Designation (Manager, Executive or Other): ");
designation = myScanner.next();
System.out.println("Enter Basic Salary: ");
basicSalary = myScanner.nextInt();
}
public void SetBonus()
{
if(basicSalary < 1500){
bonus = 0.0;
}
else if(basicSalary>=1500 && basicSalary<3000){
bonus = basicSalary * (12.0/100.0);
}
else if(basicSalary>=3000 && basicSalary<5000){
bonus = basicSalary * (15.0/100.0);
}
else{
bonus = basicSalary * (25.0/100.0);
}
}
public void SetCommission()
{
if( empDept.equalsIgnoreCase("other") ){
commission = 0.0;
}
else if( empDept.equalsIgnoreCase("marketing") && designation.equalsIgnoreCase("manager") ){
commission = basicSalary * (30.0/100.0);
}
else if( empDept.equalsIgnoreCase("marketing") && designation.equalsIgnoreCase("executive") ){
commission = basicSalary * (15.0/100.0);
}
else if( empDept.equalsIgnoreCase("marketing") && designation.equalsIgnoreCase("other") ){
commission = basicSalary * (10.0/100.0);
}
else{
commission = 0.0;
}
}
public void SetNssf()
{
if(basicSalary < 1500){
nssf = basicSalary * (5.0/100.0);
}
else if(basicSalary>=1500 && basicSalary<3000){
nssf = basicSalary * (8.0/100.0);
}
else if(basicSalary>=3000 && basicSalary<5000){
nssf = basicSalary * (12.0/100.0);
}
else if(basicSalary>=5000 && basicSalary<7000){
nssf = basicSalary * (15.0/100.0);
}
else if(basicSalary>=7000 && basicSalary<10000){
nssf = basicSalary * (20.0/100.0);
}
else{
nssf = basicSalary * (25.0/100.0);
}
}
public void SetNetSalary()
{
netSalary = ( basicSalary + commission + bonus ) - nssf;
}
public void GetPayroll()
{
System.out.println("\n\nPayroll Details \n _____________________");
System.out.println("ID:\t\t" + empID);
System.out.println("name:\t\t" + empName);
System.out.println("Bonus:\t\t" + bonus);
System.out.println("Commission:\t"+commission);
System.out.println("NSSF:\t\t"+nssf);
System.out.println("Net Salary:\t"+netSalary);
}
}
This is the second program
import java.util.Scanner;
public class display{
public static void main(String[]args){
Scanner scan = new Scanner(System.in);
int counter;
int limit;
System.out.println("How many employess do u want to enter?\n Enter here: ");
limit = scan.nextInt();
int[] a = new int[limit];
payroll2 payroll = new payroll2();
for(counter=1; counter<=limit; counter++){
System.out.println("\n\nEnter employee "+counter+" details\n");
payroll.SetPayrollDetail();
payroll.SetBonus();
payroll.SetCommission();
payroll.SetNssf();
payroll.SetNetSalary();
}
for(counter=1; counter<=limit; counter++){
payroll.GetPayroll();
//System.out.println(a);
}
}
}
This is the area of code that there's a problem in:
for(counter=1; counter<=limit; counter++){
System.out.println("\n\nEnter employee "+counter+" details\n");
payroll.SetPayrollDetail();
payroll.SetBonus();
payroll.SetCommission();
payroll.SetNssf();
payroll.SetNetSalary();
}
for(counter=1; counter<=limit; counter++){
payroll.GetPayroll();
//System.out.println(a);
}
If you think about what this does. So a payroll2 object is a single entity. When you enter them in the first for loop, you create one person. Then if you loop through that a second or third time, you overwrite that person, since you are saving to the same variable.
Then when you loop through the second loop, you are printing the payroll entity, which holds the value of the last entered person. Since the other data gets overwritten, its no surprise that you get the same guy printed limit times.
What you will want to do is build an array of payroll entities. This code accomplishes this:
payroll2[] PayrollList = new payroll2[limit]; // establish the array with correct size
for(counter=0; counter<=limit - 1; counter++){ // bounds of the array are 0 to limit - 1
payroll = new payroll(); // hard reset of the variable to make sure data is cleared
System.out.println("\n\nEnter employee "+counter+" details\n");
payroll.SetPayrollDetail();
payroll.SetBonus();
payroll.SetCommission();
payroll.SetNssf();
payroll.SetNetSalary();
PayrollList[counter] = payroll; // adds it to the array at position counter
}
for(counter=0; counter<=limit - 1; counter++){
PayrollList[counter].GetPayroll(); // gets the payroll2 object from the array and calls its function
}
DISCLAIMER: I have not run the modified code through a compiler, so it may not be 100% syntax correct, but it is very close.
I have programmed a Worker class and the driverclass for Worker..
My working class is compiling fine and showing the desired output..
But in array and StringTokenizer I am facing the main problem... And in line 32 of TestWorker.java there is an error, and I donot know why is it giving
The question is...
(i)Declare an array that can store the references of up to 5 Worker objects constructed with the data(name,workerID and hourlyRate).
(ii)And now allow the users to enter workerID and hours repeatedly until user enter an empty string. Read these values and invoke the method addWeekly() on the appropriate object (by searching through the array to locate the object with the specified ID). If a nonexistent ID is entered, display an appropriate error message.
(iii)Compute and display the salary for all the workers
Please see my codes below.....
//Worker.java
public class Worker {
public final double bonus=100;
protected String name, workerID;
protected double hourlyRate, totalHoursWorked,tax,grossSalary,netSalary;
public Worker(){
}
public Worker(String name, String workerID, double hourlyRate){
this.name = name;
this.workerID = workerID;
this.hourlyRate = hourlyRate;
}
public void addWeekly(double hoursWorked){
this.totalHoursWorked = this.totalHoursWorked + hoursWorked;
}
public double gross(){
grossSalary = (totalHoursWorked*hourlyRate);
if(totalHoursWorked>=150){
grossSalary = grossSalary +100;
}
return grossSalary;
}
public double netAndTax(){
netSalary = grossSalary;
if(grossSalary>500){
tax = (grossSalary - 500) *0.3;
netSalary = (grossSalary - tax);
}
return netSalary;
}
public String getName(){
return this.name;
}
public String getWorkerID(){
return this.workerID;
}
public double getHourlyRate(){
return this.hourlyRate;
}
public double getTotalHours(){
return totalHoursWorked;
}
public double getGrossSalary(){
return grossSalary;
}
public void addToGross(double amt){
grossSalary = grossSalary + amt;
}
public void displaySalary(){
System.out.print("Name: " +getName() + "\nID :" + getWorkerID()
+ "\nHourly Rate: " + getHourlyRate()+ "\nTotalHours Worked" + getTotalHours() +
"\nGross pay" + getGrossSalary() + "\nTax: " + netAndTax() +
"\nNet Pay: " + netAndTax());
}
}
//TestWorker.java
import java.util.Scanner;
import java.util.StringTokenizer;
public class TestWorker {
public static void main(String args[]){
Worker e = new Worker("John Major","s123",15.0);
e.addWeekly(45);
e.addWeekly(40);
e.addWeekly(32);
e.addWeekly(38);
e.gross();
e.netAndTax();
e.displaySalary();
Worker[] worklist = new Worker[5];
worklist[0] = new Worker("Richard Cooper","s1235",20.0);
worklist[1] = new Worker("John Major","s1236",18.0);
worklist[2] = new Worker("Mary Thatcher","s1237",15.0);
worklist[3] = new Worker("David Benjamin","s1238",16.0);
worklist[4] = new Worker("Jack Soo","s1239",25.0);
Scanner input = new Scanner(System.in);
String name;
double hourly;
do{
System.out.println("\n");
System.out.print("Please Enter ID and hours-worked in a given week: ");
name = input.nextLine();
StringTokenizer string = new StringTokenizer(name,"+");
String[] array =new String[(string.countTokens)];
for(int i=0;i<=4;i++){
if(array[0].equals(worklist[0])){
e.getName();
e.getWorkerID();
e.addWeekly(Double.parseDouble(array[0]));
e.gross();
e.displaySalary();
}
else if(array[0].equals(worklist[1])){
e.getName();
e.getWorkerID();
e.addWeekly(Double.parseDouble(array[1]));
e.gross();
e.displaySalary();
}
else if(array[0].equals(worklist[2])){
e.getName();
e.getWorkerID();
e.addWeekly(Double.parseDouble(array[2]));
e.gross();
e.displaySalary();
}
else if(array[0].equals(worklist[3])){
e.getName();
e.getWorkerID();
e.addWeekly(Double.parseDouble(array[3]));
e.gross();
e.displaySalary();
}
else if(array[0].equals(worklist[4])){
e.getName();
e.getWorkerID();
e.getHourlyRate();
e.addWeekly(Double.parseDouble(array[4]));
e.gross();
e.displaySalary();
}
else{
System.out.println("Please Enter correct information");
}
}
System.out.println();
while(string.hasMoreElements()){
System.out.println(string.nextElement());
}
}
while(name.isEmpty()==false);
}
}
Firstly, you've specified countTokens as a field when it is actually a method on this line:
String[] array = new String[(string.countTokens)]; // Incorrect
String[] array = new String[(string.countTokens())]; // Correct
Now you seem to be splitting the input on a + sign? So you're expected input is something along the lines of s123+12 which would mean ID s123 worked 12 hours this week. So in order to solve something like you probably want a loop that looks like this:
Scanner input = new Scanner(System.in);
System.out.println("\n");
System.out.print("Please Enter ID and hours-worked in a given week: ");
String enteredString = input.nextLine();
while (!enteredString.isEmpty()) {
StringTokenizer stringtok = new StringTokenizer(enteredString, "+");
String id = stringtok.nextToken();
Double hours = Double.parseDouble(stringtok.nextToken());
for (int i = 0; i < 5; i++) {
if (worklist[i].getWorkerID().equals(id)) {
worklist[i].addWeekly(hours);
break;
}
}
System.out.println("\n");
System.out.print("Please Enter ID and hours-worked in a given week: ");
enteredString = input.nextLine();
}
for (int i = 0; i < 5; i++) {
worklist[i].gross();
worklist[i].netAndTax();
worklist[i].displaySalary();
}
Keep in mind that this is very rough and I'm not entirely clear from your instructions on what exactly you are trying to achieve.
Why not consider String.split() name.split("\\+") that will give you a string array