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];
}
Related
I have this code where you would search for the patient ID and when found a sub menu will show, the user would then be prompted to choose. If the user chooses bill the would then be asked to enter a transaction and it would be summed to the balance in the same object as the ID that was searched. However when the user inputs a value it always sums the value to the balance(450) in the object.
How can I fix this?
NB: it's in an array
output: adds the input to the first object only.
patient pAccount[] = new patient [10];
patient p1 = new patient("Jabari","luck",d1 ,"234-4343", "p01" ,450);
patient p2 = new patient("Lisa", "nun", d2,"311-5634" , "p02",300);
patient p3 = new patient("Kyle", "Hep",d3 ,"555-5555" , "p03",2000 );
//search array for patient ID
public static void ID(person [] pAccount) {
Scanner scan= new Scanner(System.in);
String num = scan.next();
for(int i=0; i< pAccount.length; i++) {
if (pAccount[i].getpatID().equals(num)) {
System.out.println("found");
break;
}
}
}
//sum user input to balance
public static void bill(person[] pAccount) {
Scanner in = new Scanner (System.in);
double sum;
double num= in.nextDouble();
for(int i=0; i <= pAccount.length; i++) {
person ad= pAccount[i];
sum = ((patient) ad).getbalance()+ num;
System.out.println("Balance: " +sum);
break;
}
}```
what I understood from your question is, you need to add sum to the balance of a specific object in Patient Object array. Below is the way to do,
(I excluded few member variables which I didn't get just by looking at Object creation in your question and kept only name, patId and balance in Patient Class. Also I assumed you've Constructor with all the fields)
I took your code and modified a little for you requirement. You can refer comments I added in the code snippets.
PatientMainClass.class
public class PatientMainClass {
public static void main(String[] args) {
Patient pAccount[] = new Patient[3];
Patient p1 = new Patient("Jabari", "p01", 450);
pAccount[0] = p1;
Patient p2 = new Patient("Lisa", "p02", 300);
pAccount[1] = p2;
Patient p3 = new Patient("Kyle", "p03", 2000);
pAccount[2] = p3;
//Use bill method to add Amount to existing balance of all the Patient Objects
Patient.bill(pAccount);
System.out.println();
for (int i = 0; i < pAccount.length; i++) {
System.out.println("After adding amount to the Balance of pAccount[" + i + "] is : " + pAccount[i].getBalance());
}
System.out.println();
//Use billToSpecific method to add Amount to specific Patient Object
//to billToSpecific method, pass both Patient Array and Patient ID to which you want to add Amount
Patient.billToSpecificPatient(pAccount, "p02");
System.out.println();
for (int i = 0; i < pAccount.length; i++) {
System.out.println("After adding amount to p02, Balance of pAccount[" + i + "] is : " + pAccount[i].getBalance());
}
} }
Patient.class
public class Patient {
private String name;
private String patId;
private double balance;
public Patient(String name, String patId, double balance) {
super();
this.name = name;
this.patId = patId;
this.balance = balance;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPatId() {
return patId;
}
public void setPatId(String patId) {
this.patId = patId;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
// This method will Add entered value i.e.. "num" to the Balance of all the Patient Objects
public static void bill(Patient[] pAccount) {
System.out.println("In bill method"); // Always try using System.out.println for Debugging
Scanner in = new Scanner(System.in);
double sum;
double num = in.nextDouble();
for (int i = 0; i < pAccount.length; i++) {
Patient ad = pAccount[i];
sum = ((Patient) ad).getBalance() + num;
ad.setBalance(sum);
System.out.println("Balance: " + sum);
// break; // Commenting break statement to add balance to all the Objects
}
}
// This method will Add entered value i.e.. "num" to the Balance of the Specific Patient Object
public static void billToSpecificPatient(Patient[] pAccount, String patId) {
System.out.println("In billToSpecific method"); // Always try using System.out.println for Debugging
Scanner in = new Scanner(System.in);
double sum;
double num = in.nextDouble();
for (int i = 0; i < pAccount.length; i++) {
if (pAccount[i].getPatId().equals(patId)) {
Patient ad = pAccount[i];
sum = ((Patient) ad).getBalance() + num;
ad.setBalance(sum);
System.out.println("Balance: " + sum);
break; // Using break statement to exit the loop once we add amount to specific Patient Object
}
}
} }
I guess, you can now resolve your issue with the help of these code snippets. Hope it is helpful.
Purpose: "Write a payroll class using 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: 568845, 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 double 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 throught he subscipts. The class should have a method
that accepts an employee's identification number as an argument and returns the gross pay for that
employee."
Set/Get Methods with Grosspay Method:
public class Payroll{
private int [] employeeID ={5658845, 4520125, 7895122, 8777541, 8451277, 1302850, 7580489};
private int [] hours = new int [7];
private double [] wages = new double [7];
private double [] payRate = new double [7];
public void setEmployeeID(int a, int emp){
employeeID[a] = emp;
}
public void setHours(int a, int hr){
hours[a] = hr;
}
public void setWages(int a, int wgs){
wages[a] = wgs;
}
public void setPayrate(int a, int prt){
payRate[a] = prt;
}
public int getEmployeeID(int a){
return employeeID[a];
}
public int getHours(int a){
return hours[a];
}
public double getWages(int a){
return wages[a];
}
public double getPayrate(int a){
return payRate[a];
}
public void Grosspay(){
for(int a = 0; a < 7; a++){
wages[a] = hours[a] * payRate[a];
}
}
}
Where everything is executed:
import java.util.Scanner;
public class TestPayroll{
public static void main(String [] args){
Scanner in = new Scanner(System.in);
Payroll pr = new Payroll();
int hr;
double prt;
for (int a = 0; a < 7; a++){
System.out.println("Enter in the hours worked by employee " + pr.getEmployeeID(a));
hr = in.nextInt();
pr.setHours(a,hr);
while(hr < 0){
System.out.println("Enter in a number greater than 0");
hr = in.nextInt();
pr.setHours(a,hr);
}
System.out.println("Enter in the pay rate for employee " + pr.getEmployeeID(a));
prt = in.nextDouble();
while(prt < 6.00){
System.out.println("Enter in a payrate greater than 6.00");
prt = in.nextDouble();
}
}
pr.Grosspay();
for(int a = 0; a < 7; a++){
System.out.println("Employee " + pr.getEmployeeID(a) + " has a gross pay of " + pr.getWages(a));
}
}
I run the program and everything works fine except when it prints out wages. Instead of the wages being the result of hours[a] * payRate[a], it prints out 0.0. I'm thinking that Grosspay method may not be functioning the way I think it should be functioning. Or it could be that I set wages[a] = wgs but wgs is not being used in the code so nothing gets stored in the wages array. So what is wrong with my code that 0.0 is being printed out? Any help is appreciated.
Try this
Payroll.class
private int [] employeeID ={5658845, 4520125, 7895122, 8777541, 8451277, 1302850, 7580489};
private int [] hours = new int [7];
private double [] wages = new double [7];
private double [] payRate = new double [7];
public void setEmployeeID(int a, int emp){
employeeID[a] = emp;
}
public void setHours(int a, int hr){
hours[a] = hr;
}
public void setWages(int a, int wgs){
wages[a] = wgs;
}
public void setPayrate(int a, double prt){
payRate[a] = prt;
}
public int getEmployeeID(int a){
return employeeID[a];
}
public int getHours(int a){
return hours[a];
}
public double getWages(int a){
return wages[a];
}
public double getPayrate(int a){
return payRate[a];
}
public void Grosspay(){
for(int a = 0; a < 7; a++){
wages[a] = hours[a] * payRate[a];
}
}
Main.class
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Payroll pr = new Payroll();
int hr,wgs = 0;
double prt;
for (int a = 0; a < 7; a++){
System.out.println("Enter in the hours worked by employee " + pr.getEmployeeID(a));
hr = 1;
pr.setHours(a,hr);
while(wgs <= 0){
System.out.println("Enter in a number greater than 0");
wgs = 1;
pr.setWages(a,wgs);
}
System.out.println("Enter in the pay rate for employee " + pr.getEmployeeID(a));
prt = 1;
while(prt < 6.00){
System.out.println("Enter in a payrate greater than 6.00");
prt = 7;
pr.setPayrate(a,prt);
}
}
pr.Grosspay();
for(int a = 0; a < 7; a++){
System.out.println("Employee " + pr.getEmployeeID(a) + " has a gross pay of " + pr.getWages(a));
}
}
I know that java can't normally return two values, but I'm trying to return the value as a method.. From there I want to use the values of score1 and maxScore1 in a string in the main method. getHwGrades is the method I'm having issues with. I get "error: cannot find symbol". I'm not allowed to use arrays for this program. On another note, I'm also not supposed to use any if/else statements, but I could not find any other way to limit the value of discussionGrade to 20. Any help is appreciated
import java.util.Scanner;
public class Grades
{
public static void main(String[] args)
{
Scanner getG = new Scanner(System.in);
int weight1;
int weight2;
int weight3;
int score2 = 0;
int maxScore2 = 0;
int sections;
int discussionGrade;
System.out.println("What is the weight for the HW and Exam 1?");
weight1 = getG.nextInt();
weight2 = getG.nextInt();
weight3 = getWeight(weight1, weight2);
System.out.println("Using weights of " + weight1 + " " + weight2 + " " + weight3);
getHwGrades();
sections = numberSections();
discussionGrade = calcDGrade(sections);
System.out.println("What is your grade for exam1?"); //move under hw total points and final grade, add curve
score2 = getG.nextInt();
maxScore2 = getG.nextInt();
System.out.println("Total Points =" + (score1+ discussionGrade) + "/ "(maxScore1 + 20));
}
public static int getHwGrades()//method for asking and storing hw grades
{
int score1;
int maxScore1;
int nOfA;
Scanner getG = new Scanner(System.in);
System.out.println("How many HW assignments are there?");
nOfA = getG.nextInt();
for (int i = 1; i <= nOfA; i++) //loop that asks for the grades corresponding to the amount of hw assignments there were
{
System.out.println("What is your grade and then the max grade for assignment " + i + "?");
score1 += getG.nextInt();
maxScore1 += getG.nextInt();
}
return new getHwGrade(score1, maxScore1); //returns results of inputs into method holding the 2 variables
}
public static int numberSections() //finds out how many sections the student attended
{
Scanner getG = new Scanner(System.in);
System.out.println("How many sections did you attend?");
return getG.nextInt();
}
public static int calcDGrade(int sections) //method to calculate the grade for the students sections
{
int maxDGrade = ((sections*4)); if (maxDGrade > 20) //limits total score to 20
{
return 20;
}
else
{
return maxDGrade;
}
}
public static int getWeight(int weight1, int weight2)//returns the weight that will be used for weight3
{
return (100-(weight1 + weight2));
}
public static double round2(double number)
{
return Math.round(number * 100.0) / 100.0;
}
}
Since you can only return a single value, you need to return a single value. :-) Normally if a method needs to return complex information, the way you have it do that is either:
Return a newly-created instance of a class that has fields for the individual pieces of information
Have the method fill in an instance of such a class that's passed to it (usually not ideal barring a good reason for doing it)
So for instance:
class HwGrades {
private int score1;
private int maxScore1;
ScoreInfo(int _score1, int _maxScore1) {
this.score1 = _score1;
this.maxScore1 = _maxScore1;
}
// ...accessors as appropriate, presumably at least getters...
}
Then return an instance of HwGrades from getHwGrades:
public static int getHwGrades()//method for asking and storing hw grades
{
int score1;
int maxScore1;
// ...
return new HwGrades(score1, maxScore1);
}
If you needed, you could further decouple things by making HwGrades an interface, which you then implement with a private class, so that the API isn't tied to a specific class. Almost certainly overkill for a small school project.
getHwGrade is expected to be a class.
Have a class like this
class getHwGrade{
int a;
int b;
public getHwGrade(int a,b){
this.a=a;this.b=b;
}
Can someone help me figure out how to make this program display the longest streak. I'm rolling two dice, and recording the percent each dice sum. Now I need something that will tell me what dice sum came up in the longest streak for example "The longest run was a run of 8 7's that began at roll 1479966."
import java.util.Scanner;
import java.text.DecimalFormat;
public class RollThoseDice {
/* Author: Name
* Assignment: Third Program
*/
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
int timesRolled, randomOutSum;
DecimalFormat df = new DecimalFormat ("#.###");
System.out.println("Name: "
+ "\nAssignment: Third Program"
+"\nExtra Credit: Percentage is displayed in three decimal places");
int[] d = new int[13];
for (int i = 2; i < 13; i++) d[i] = 0;
int N=0;
boolean againA = true;
while(againA) {
try{
System.out.print("\nHow Many Rolls? ");
N =kbd.nextInt();
againA = false;
} catch(Exception e) {
System.out.println("Invalid Input");
kbd.next();
}
}
for (int k = 0; k < N; k++) {
int diceOut1 = (int) (Math.random()*6+1);
int diceOut2 = (int) (Math.random()*6+1);
int diceSum = diceOut1 + diceOut2;
d[diceSum]++;
}
for (int i = 2; i < 13; i++)
System.out.println("Total " + i + " happened "
+ df.format((double) (d[(int) i] / (double) N) * 100)
+ "% of the time.");
}
}
The longest run was a run of 8 7's that began at roll 1479966.
So, what are the parameters in that output?
Looks like roll, run length or roll count, and roll number.
Hmm, what can keep multiple variables, so we can treat them as one thing?
I know, we'll create a model class.
public class RollStreak {
private final NumberFormat NF = NumberFormat.getInstance();
private int roll;
private int rollCount;
private long rollNumber;
public RollStreak(int roll, long rollNumber, int rollCount) {
this.roll = roll;
this.rollNumber = rollNumber;
this.rollCount = rollCount;
}
public int getRoll() {
return roll;
}
public int getRollCount() {
return rollCount;
}
public long getRollNumber() {
return rollNumber;
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("The computer rolled a ");
builder.append(roll);
builder.append(" ");
builder.append(rollCount);
builder.append(" times in a row starting at roll number ");
builder.append(NF.format(rollNumber));
builder.append(".");
return builder.toString();
}
}
A model class allows you to treat a group of fields as one object.
I don't want to give away the whole answer. You still have to determine how to create these model class instances and get the longest streaks. Hint: There can be more than one longest streak.
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