Java: Exception in thread "main" java.lang.NullPointerException - java

I keep getting this error when I run this code and I do not know how to fix it. I've been doing Java for about 3 months now and could use some help. Basically the program asks the user to enter in the pay rate and the hours for each employee. Pay rate, hours and employee number are all arrays that are going to share the same index with each other. When the user enters in the pay rate and hours for the employee, the program returns the gross pay for that employee. Except this error keeps popping up. Please help!
Exception in thread "main" java.lang.NullPointerException
at chapter.pkg7.lab.Payroll.setPayRate(Payroll.java:41)
at chapter.pkg7.lab.Chapter7Lab.main(Chapter7Lab.java:45)
Java Result: 1
Here's the code:
package chapter.pkg7.lab;
import java.util.Scanner;
public class Chapter7Lab {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
Payroll newEmployee = new Payroll();
int[] employeeNum = newEmployee.getEmployeeID();
double pay;
int hour;
for (int i = 0; i < employeeNum.length; i++)
{
System.out.println("Please enter the Pay Rate for Employee #" + employeeNum[i]);
pay = keyboard.nextDouble();
newEmployee.setPayRate(pay, i);
System.out.println("Please enter the hours for Employee #" + employeeNum[i]);
hour = keyboard.nextInt();
newEmployee.setHours(hour, i);
System.out.println("Gross pay is: " + newEmployee.getWages(i));
}
package chapter.pkg7.lab;
public class Payroll {
private int[] employeeID = new int[] {5658845, 4520125, 7895122,
8777541, 8451277, 1302850, 7580489};
private int[] hours;
private double[] payRate;
private double wages;
public double getWages(int index) {
wages = hours[index] * payRate[index];
return wages;
}
//Accessors and Mutators
public int[] getEmployeeID() {
return employeeID;
}
public void setEmployeeID(int[] employeeID) {
this.employeeID = employeeID;
}
public int[] getHours() {
return hours;
}
public void setHours(int hours, int index) {
this.hours[index] = hours;
}
public double[] getPayRate() {
return payRate;
}
public void setPayRate(double payRate, int index) {
this.payRate[index] = payRate;
}
}

You've declared payRate (and hours and wages) as arrays, but it's an uninitialized instance variable, so it's null.
Initialize it:
private double[] payRate = new double[employeeID.length];
(and likewise for hours and wages).

Add a constructor to your Payroll class that initialises the two arrays hours and payRate like this:
public Payroll(){
hours = new int[employeeID.length];
payRate = new double[employeeID.length];
}
Then when you create the Payroll object in your main class as you're currently doing with the line: Payroll newEmployee = new Payroll(); the arrays will be initialised.

NullPointerException
Arise when you won't initialize variable or object and try to access that varibale or object

Related

I am not able to get it do the deductions right on payroll program in java. error I am getting is one of my variables has not been initialized

I am getting an error that says: C:\Users\Jasmi\payroll\src\Payroll.java:68:38
java: variable grossPay might not have been initialized, but I am not sure how to fix it.
public class Payroll {
public String calculateGrossPay;
public String calculateNetPay;
private String name;
private int idNumber;
private double hourlyPayRate;
private double hoursworked;
Payroll(String nameGiven, int idNumbergiven) {
name = nameGiven;
idNumber = idNumbergiven;
hourlyPayRate = 7.15;
hoursworked = 0;
}
public String getName() {
return name;
}
public int getIDNumber() {
return idNumber;
}
public double getHourlyPayrate() {
return hourlyPayRate;
}
public double getHoursWorked() {
return hoursworked;
}
public void setName(String nameGiven) {
name = nameGiven;
}
public void setIDNumber(int idNumbergiven) {
idNumber = idNumbergiven;
}
public void setHourlyPayRate(double hourlypayrategiven) {
hourlyPayRate = hourlypayrategiven;
}
public void setHoursWorked(double hoursworkedgiven) {
hoursworked = hoursworkedgiven;
}
//gross pay plus overtime
public double calculateGrossPay() {
double overtime;
overtime = 0;
double grossPay;
if (hoursworked < 40) grossPay = hourlyPayRate * hoursworked;
else {
overtime = hoursworked - 40;
grossPay = (overtime * 1.5 * hourlyPayRate) + (40 * hourlyPayRate);
}
return grossPay;
}
//deductions
public double calculateNetPay() {
double netPay;
double grossPay;
double deduction = (.2579) * grossPay;
return netPay;
}
}
Here is the second document:
import javax.swing.JOptionPane;
public class PayrollClassTest {
public static void main(String[] args) {
String userInputString;
String userName;
int userId;
double userhourlyPayRate;
double userHoursworked;
userName = JOptionPane.showInputDialog("enter the name of this employee: ");
userInputString = JOptionPane.showInputDialog("Please enter employee ID: ");
userId = Integer.parseInt(userInputString);
userInputString = JOptionPane.showInputDialog("Please enter Hourly Pay Rate: ");
userhourlyPayRate = Double.parseDouble(userInputString);
userInputString = JOptionPane.showInputDialog("Enter the hours worked: ");
userHoursworked = Double.parseDouble(userInputString);
Payroll payroll1 = new Payroll(userName, userId);
payroll1.setHourlyPayRate(userhourlyPayRate);
payroll1.setHoursWorked(userHoursworked);
System.out.println(payroll1.getName() + " has a gross pay of " + payroll1.calculateGrossPay());
System.out.println(payroll1.getName() + " has a net pay of " + payroll1.calculateNetPay());
System.exit(0);
}
private static void calculateGrossPay() {
}
private static void calculateNetPay() {
}
}
I have tried to change deductions to be shown as this:
//deductions
public double calculateNetPay() {
double netPay = 0;
double grossPay = 0;
double deduction = (.2579) * grossPay;
return netPay;
}
}
It does work, but the results do not show the deductions:
Here is an example of the results:
Betty has a gross pay of 13000.0
Betty has a net pay of 0.0
Process finished with exit code 0
This is when I put name as Betty, gross pay as 100, and hours worked as 100. It shows the overtime correctly, but not the deductions.
Any help is greatly appreciated. thanks!
If my understanding of the code is correct then the following is where you are wrong for this piece of code.
public double calculateNetPay() {
double netPay = 0;
double grossPay = 0;
double deduction = (.2579) * grossPay;
return netPay;
}
First: netPay has no value assigned
This method will always return 0.
Reason : The netPay variable is declared and initialized to 0.
What you probably want to do before your return statement is perhaps;
netPay = grossPay - deduction;
I could be wrong in that logic, but I am definitely right when I say that you need to put some value to netPay before you return it.
Second: grossPay has no value assigned
In this method, you multiple .2579 with grossPay, but grossPay is 0 that you have now initialized.
You are assuming that the variable grossPay is shared for the two methods calculateGrossPay and calculateNetPay.
That is not true.
These are both two separate local variables that are declared separately in two different methods and have two different scopes.
You can read more about scope of java variables here:
variable docs from oracle
"in scope" meaning in java : StackOverflow question
My recommendation is to make grossPay a class variable instead of a method variable so that it could be shared between the two methods of the same class instance. (Assuming you are calling calculateGrossPay before calculateNetPay every time, so that grossPay can have the right value assigned to it.)

JAVA Get & Set methods with calculations

new to Java and trying to set up get and set methods. Although one I need to do as calculation based off getSalary() multiplied by getMonths() to get a Year to Date total.
I haven't been able to find out if calculations are possible in get or set methods or I may just be such a newbie I have it in the wrong place.
public class Employee_v2
{
//Instance variables
private String first_name;
private String last_name;
private double salary;
private int months;
final double increase= 0.25;
private double year_to_date;
public Employee_v2()
{
//fill in the code to set default values to the instance variables
first_name="";
last_name="";
salary= 0.0;
months= 0;
}
//Constructor initializing instance variables with arguments
public Employee_v2(String f, String l, Double sal, int mo)
{
first_name = f;
last_name = l;
salary = sal;
months = mo;
}
//set arguments
public void setFirst(String f)
{
first_name = f;
}
public void setLast (String l)
{
last_name = l;
}
public void setSalary (double sal)
{
salary = sal;
}
public void setMonths (int mo)
{
months = mo;
}
public void setYtdSalary ()
{
double yearToDateSal;
yearToDateSal = getSalary() * getMonths();
}
//get arguments
public String getFirst()
{
return first_name;
}
public String getLast()
{
return last_name;
}
public double getSalary()
{
return salary;
}
public int getMonths()
{
return months;
}
public double getYtdSalary()
{
return yearToDateSal;
}
//DISPLAY
public void displayEmployee()
{
//display the name and salary of both Employee objects
System.out.println("Employee first name: " + getFirst());
System.out.println("Employee last name: " + getLast());
System.out.printf("Employee salary: $%.2f\n", getSalary());
//complete the code
System.out.println("-------------------------------");
//Determine the year to date salary for both employee
System.out.printf(getFirst() + "'s salary: $%.2f\n", getSalary());
// System.out.println(jas.getSalary());
System.out.printf("Year to date salary: $%.2f\n", getYtdSalary());
//set and display salary with increase
setSalary(getSalary()+ getSalary()*increase);
System.out.printf("New Salary: $%.2f\n", getSalary());
System.out.println();
System.out.println();
}//end method
}//end Class
Calculation are possible in getter and setter. I would do something like this:
public double getYtdSalary(){
double ytd = 0;
ytd = months * salary;
return ytd;
}
Like this you can calculate the year to date on the fly and is always accurate data. For example if you called the setMonths method you would also have to call the setYtdSalary before calling the getYtdSalary.
Also there is no need to call your getters in your class to access your private variables.
I would also suggest using Javadoc comment in your classes as they make it easier to understand what the methods do.
to answer your question: yes it is possible to do calculations
this is also needed in many places, as the main reason to use get and set methods is so you can check or manipulate the values before setting them in your class
I guess your Code will Crash on the printing of the year to date Salary, because the variable yearToDateSal is only valid in the Scope of your set Method.
public void setYtdSalary ()
{
double yearToDateSal;
yearToDateSal = getSalary() * getMonths();
}
you should declare your YearToDateSal variable in the beginning of the class, i.e. rigth after
final double increase= 0.25;
private double year_to_date;
private double yearToDateSal;
and in your setYtdSalary() remove the declaration of yearToDateSal;
this way you should be fine :)

How can i calculate the value(s) of which some are double?

The code I wrote compiles well, but there are certain values that do not calculate. The rate and hours value, tuition and .08 do not calculate. Maybe my code is wrong or something. I am still new to java so i am trying my best. Here is my code:
import java.io.*;
import java.text.DecimalFormat;
import java.util.Scanner;
public class Tuition
{
static double fees;
static double rate;
static double tuition;
private static Scanner sc;
public static void main(String[] args) throws IOException
{
//declare variables
int hours;
//call methods
displayWelcome();
hours = getHours();
rate = getRate(hours);
tuition = calcTuition(hours, rate);
fees = calcFees(tuition);
}
public static void displayWelcome()
{
//welcome statement
System.out.println("Welcome to school that offers distance learning courses");
}
public static int getHours()
{
//declare method variables
int hours = 0;
//a user must enter a string value
System.out.println("Enter total number of hours");
sc = new Scanner(System.in);
try
{
hours = sc.nextInt();
}
catch(NumberFormatException e)
{
System.out.print("Incorrect number");
}
return hours;
}
public static double getRate(int hours)
{
if (hours > 15)
{
System.out.println("rate per credit hour is 44.50");
}
else
{
System.out.println("rate per credit hour is 50.00");
}
return rate;
}
public static double calcTuition(int hours, double rate)
{
tuition =(double)rate * hours;
System.out.print("tuition is" + (tuition));
return tuition;
}
public static double calcFees(double tuition)
{
fees =(double)tuition * .08;
System.out.print("fees are" + (fees));
return fees;
}
public static void displayToatal(double total)
{
DecimalFormat twoDigits = new DecimalFormat("$#,000.00");
System.out.println("the total value is"+ twoDigits.format(tuition + fees));
}
}
In calcTuition()
tuition =(double)rate * hours;
should be
tuition =rate * (double)hours;
: )
You aren't setting the rate. You need a line of code that looks like "rate = x;". You only have println's in the getRate method, but you don't actually set the variable to equal anything.

How do I create a class with arrays and then pass values to a program?

I have an assignment for my class that goes like this:
"Write a Payroll class that uses the following arrays as fields:
employeeID - An array of seven integers to hold employee identification numbers.
The array should be initialized with the following numbers:
5658845 4520125 7895122 8777541 8451277 1302850 7580489
hours - An array of seven integers to hold the number of hours worked by each employee.
payRate - An array of seven doubles to hold each employee's hourly pay rate.
wages - An array of seven doubles to hold each employee's gross wages.
The class should relate the data in each array through the subscripts.
For example, the number in element 0 of the hours array should be the number of hours worked by the employee
whose identification number is stored in element 0 of the employeeID array.
That same employee's pay rate should be stored in element 0 of the payRate array.
In addition to the appropriate accessor and mutator methods,
the class should have a method that accepts an employee's identification number
as an argument and returns the gross pay for that employee.
I'm having trouble passing values from the program I created. Here is the class:
public class moduleArray2
{
final int NUM_EMPLOYEES = 7;
int[] employeeID = {5658845, 4520125, 7895122, 8777541, 8451277, 1302850, 7580489};
int[] hours = new int[NUM_EMPLOYEES];
double[] payRate = new double[NUM_EMPLOYEES];
double[] wages = new double[NUM_EMPLOYEES];
int employee = 0;
double wage = 0;
// setHours method
public void setHours(int[] time)
{
time = hours;
}
// setPayRate method
public void setPayRate(double[] pay)
{
pay = payRate;
}
// setWages method
public void setWage(int[] time, int[] pay)
{
for (int index = 0; index < NUM_EMPLOYEES; index++)
wages[index] = time[index] * pay[index];
}
//getEmployeeID method
public int getEmployeeID(int index)
{
return employee;
}
// getWage method
public double getWage(int index)
{
return wage;
}
}
The program is supposed to display each employee number and ask the user to enter that employee's hours and pay rate. It should then display each employee's identification number and gross wages. When I run the program, it simply lists everything as a zero value, including the employee ID numbers.
import java.util.Scanner;
public class moduleArrayDemo2
{
public static void main(String[] args)
{
final int NUM_EMPLOYEES = 7;
int[] time = new int[NUM_EMPLOYEES];
double[] pay = new double[NUM_EMPLOYEES];
// Create new Scanner object
Scanner keyboard = new Scanner(System.in);
// Create employee object
moduleArray2[] employee = new moduleArray2[NUM_EMPLOYEES];
// A loop that creates objects for each element
for (int i = 0; i < employee.length; i++)
employee[i] = new moduleArray2();
for (int i = 0; i < employee.length; i++)
{
System.out.print("Enter hours for Employee #" + employee[i].getEmployeeID(i) +
": ");
time[i] = keyboard.nextInt();
employee[i].setHours(time);
System.out.print("Enter how much Employee #" + employee[i].getEmployeeID(i) +
" makes per hour: ");
pay[i] = keyboard.nextDouble();
employee[i].setPayRate(pay);
}
for (int i = 0; i < employee.length; i++)
{
System.out.println("Employee #" + employee[i].getEmployeeID(i) +
" Wages: " + employee[i].getWage(i));
}
}
}
I can do arrays in a simple program, and I can do classes with programs that create instances of those classes. Arrays in a class...I feel totally lost. How do I reference the arrays in the class to get values in the program itself? Any feedback or suggestions would be greatly appreciated!
First of all you're messing up accessor methods arguments, their actual values and accessed objects.
class ModuleArray2
int[] employeeID = {5658845, 4520125, 7895122, 8777541, 8451277, 1302850, 7580489};
int NUM_EMPLOYEES = employeeID.length; // I assume you've got it defined somewhere
int[] hours = new int[NUM_EMPLOYEES];
double[] payRate = new double[NUM_EMPLOYEES];
double[] wages = new double[NUM_EMPLOYEES];
// setHours method - will reassign the whole array of `hours` with the provided argument `time` ; I'm leaving this method with a signature that you have provided just to have a place to put my comment on it
public void setHours(int[] time) {
hours = time;
// time = hours; // this is wrong - it would assign class field value to the temporary argument variable `time`, and then just throw it away (since `time` in this scope is temporary)
}
// setHours method - will set working hours in one of an array `hours` elements specified by the provided index - number of an employee it refers to
public void setHours(int employeeNumber, int workedHours) {
hours[employeeNumber] = workedHours;
}
// setPayRate method - same as above
public void setPayRate(int employeeNumber, double payRate) {
payRates[employeeNumber] = payRate;
}
// setWage method - same as above
public void setWage(int employeeNumber, double wage) {
wages[employeeNumber] = wage;
}
// getWage method - will return the wage for employee given by an index in array number
public double getWage(int employeeNumber) {
return wages[employeeNumber];
}
//getEmployeeID method - will return an ID of employee given by an index in array number
public int getEmployeeID(int employeeNumber) {
return employeeID[employeeNumber];
}
//getEmployeeIndexFromID method - will return the index of employee given by his ID number - this is inverse function of the function 'getEmployeeID'
public int getEmployeeIndexFromID(int employeeID) {
int index;
// search implementation goes here
// you should try to write it on your own
return index;
}
}
based on the Tax program change the total variable to an array that accepts 5 double values from the user then pass it to the tax method to get the tax on the total.

Calculating with Java Arrays

first time poster here. I am at the end of my rope, ready to give up my pursuit of a career in programming. I failed to turn in my last assignment because I couldn't get my program to work. Now, I'm doing some extra practice on my own. A simple practice assignment using arrays and I can't figure out the last bit of it. Can someone please tell me what I'm doing wrong here? When I run it, I can enter the data, but the program quits prior to displaying the output with this error:
Exception in thread "main" java.lang.NullPointerException
at Payroll.getGrossPay(Payroll.java:47)
at PayrollCalc.main(PayrollCalc.java:32)
I can display hours and payRate separately, but I cannot display grossPay. I'm also not happy with my constructor, but not quite sure what to do with it. The problem required me to initialize the array in the Payroll class.
public class Payroll {
private final int NUM_EMPLOYEES = 3;
private int[] employeeId = {5658845, 4520125, 7895122}, empId, hours;
private double[] payRate, wages, grossPay;
public Payroll()
{
empId = employeeId;
}
public void setEmployeeId(int[] employeeId)
{
empId = employeeId;
}
public void setEmpHours(int[] empHoursIn)
{
hours = empHoursIn;
}
public void setEmpPayRate(double[] empPayRateIn)
{
payRate = empPayRateIn;
}
public int[] getEmployeeId()
{
return empId;
}
public int[] getEmpHours()
{
return hours;
}
public double[] getEmpPayRate()
{
return payRate;
}
public double[] getGrossPay()
{
for (int count = 0; count < NUM_EMPLOYEES; count++)
{
grossPay[count] = getEmpPayRate()[count] * getEmpHours()[count];
}
return grossPay;
}
}
import java.util.Scanner;
public class PayrollCalc
{
public static void main(String[] args)
{
int count;
final int NUM_EMPLOYEES = 3;
int[] empHours = new int[NUM_EMPLOYEES];
double[] empPayRate = new double[NUM_EMPLOYEES];
Scanner keyboard = new Scanner(System.in);
Payroll payroll = new Payroll();
for (count = 0; count < NUM_EMPLOYEES; count++)
{
System.out.print("Enter total hours for employee " +
payroll.getEmployeeId()[count] + ": ");
empHours[count] = keyboard.nextInt();
payroll.setEmpHours(empHours);
System.out.print("Enter pay rate for employee " +
payroll.getEmployeeId()[count] + ": ");
empPayRate[count] = keyboard.nextDouble();
payroll.setEmpPayRate(empPayRate);
}
System.out.println("\nEMPLOYEE ID\tGROSS PAY");
System.out.println("----------- ---------");
for (count = 0; count < NUM_EMPLOYEES; count++)
{
System.out.println(payroll.getEmployeeId()[count] + "\t\t" +
payroll.getGrossPay()[count]);
}
}
}
Thanks in advance for your help!
Stef
Doesn't look like you ever initialized the grossPay array - see if this makes a difference:
private double[] payRate, wages;
private double[] grossPay = new double[NUM_EMPLOYEES];
As a tip, when starting out it's probably best to initialize all your variables as soon as you can, which in your case is mostly at construction time. When you get a little more comfortable then you initialize when you need things - for example:
public double[] getGrossPay()
{
if (grossPay == null) {
grossPay = new double[NUM_EMPLOYEES];
for (int count = 0; count < NUM_EMPLOYEES; count++)
{
grossPay[count] = getEmpPayRate()[count] * getEmpHours()[count];
}
}
return grossPay;
}
Good luck!
Your NullPointerException is occuring here:
grossPay[count] = getEmpPayRate()[count] * getEmpHours()[count];
as you haven't initialised the double array grossPay (or payRate or wages). You could use:
private double[] grossPay = new double[NUM_EMPLOYEES];
also you'll need:
private double[] payRate = new double[NUM_EMPLOYEES];
private double[] wages = new double[NUM_EMPLOYEES];
array grossPay was never initialized inside Payroll in
public double[] getGrossPay().
you need to initialize the size of the array before using it.
probably best would be to add in constructor:
public Payroll() {
grossPay= new double[NUM_EMPLOYEES];
}

Categories

Resources