473,791 Members | 2,881 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Help with Error Exception in thread "main" java.lang.NullP ointerException

63 New Member
Expand|Select|Wrap|Line Numbers
  1. import java.text.DecimalFormat;
  2. import javax.swing.JOptionPane;
  3.  
  4. public class PayrollSystemTest {
  5.  
  6.    public static void main( String[] args )
  7.    {
  8.       String workerType;
  9.       String first;
  10.       String last;
  11.       String ssn;
  12.       int month;
  13.       int day;
  14.       int year;
  15.       float salary;
  16.       float rate;
  17.       float hourlyWage;
  18.       float hours;  
  19.  
  20.       float sales;
  21.  
  22.       DecimalFormat twoDigits = new DecimalFormat( "0.00" );
  23.  
  24.       // create Employee array
  25.       Employee employees[] = new Employee[ 5 ];
  26.  
  27.       // generically process each element in array employees
  28.       for ( int empNo = 1; empNo <=5; empNo++ ) {
  29.  
  30.  
  31.  
  32.  
  33.     workerType=JOptionPane.showInputDialog(
  34.        "Please enter the type of worker:\n\n" +
  35.        "Salaried\nHourly\nCommission\n" +
  36.        "Base Plus Commission");
  37.  
  38.  
  39.        if(workerType.equalsIgnoreCase("Salaried")){
  40.            first=JOptionPane.showInputDialog("Enter employee " + empNo + 
  41.               " first name: ");
  42.         last=JOptionPane.showInputDialog("Enter employee " + empNo +
  43.               " last name: ");
  44.         ssn=JOptionPane.showInputDialog(
  45.             "Enter employee " + empNo + " ssn: ");
  46.         month=Integer.parseInt(JOptionPane.showInputDialog(
  47.             "Enter employee " + empNo + " birth month(1-12): "));
  48.         day=Integer.parseInt(JOptionPane.showInputDialog(
  49.             "Enter employee " + empNo + " birth day(1-31): "));
  50.         year=Integer.parseInt(JOptionPane.showInputDialog(
  51.             "Enter employee " + empNo + " birth year(yyyy): "));
  52.         salary=Float.parseFloat(JOptionPane.showInputDialog(
  53.             "Enter employee " + empNo + " weekly salary: "));
  54.         employees[empNo-1] = new SalariedEmployee(first, last,
  55.               ssn, month, day, year, salary);
  56.        }
  57.  
  58.  
  59.        else if(workerType.equalsIgnoreCase("Hourly")){
  60.         first=JOptionPane.showInputDialog("Enter employee " + empNo + 
  61.               " first name: ");
  62.         last=JOptionPane.showInputDialog("Enter employee " + empNo +
  63.               " last name: ");
  64.         ssn=JOptionPane.showInputDialog(
  65.             "Enter employee " + empNo + " ssn: ");
  66.         month=Integer.parseInt(JOptionPane.showInputDialog(
  67.             "Enter employee " + empNo + " birth month(1-12): "));
  68.         day=Integer.parseInt(JOptionPane.showInputDialog(
  69.             "Enter employee " + empNo + " birth day(1-31): "));
  70.         year=Integer.parseInt(JOptionPane.showInputDialog(
  71.             "Enter employee " + empNo + " birth year(yyyy): "));
  72.         hourlyWage=Float.parseFloat(JOptionPane.showInputDialog(
  73.             "Enter employee " + empNo + " hourly wage: "));
  74.         hours=Float.parseFloat(JOptionPane.showInputDialog(
  75.             "Enter employee " + empNo + " hours worked: "));
  76.         employees[empNo-1] = new HourlyEmployee(first, last, ssn,
  77.             month, day, year, hourlyWage, hours);
  78.        }
  79.  
  80.  
  81.        else if(workerType.equalsIgnoreCase("Commission")){
  82.         first=JOptionPane.showInputDialog("Enter employee " + empNo + 
  83.               " first name: ");
  84.         last=JOptionPane.showInputDialog("Enter employee " + empNo +
  85.               " last name: ");
  86.         ssn=JOptionPane.showInputDialog(
  87.             "Enter employee " + empNo + " ssn: ");
  88.         month=Integer.parseInt(JOptionPane.showInputDialog(
  89.             "Enter employee " + empNo + " birth month(1-12): "));
  90.         day=Integer.parseInt(JOptionPane.showInputDialog(
  91.             "Enter employee " + empNo + " birth day(1-31): "));
  92.         year=Integer.parseInt(JOptionPane.showInputDialog(
  93.             "Enter employee " + empNo + " birth year(yyyy): "));
  94.         sales=Float.parseFloat(JOptionPane.showInputDialog(
  95.             "Enter employee " + empNo + " weekly sales: "));
  96.         rate=Float.parseFloat(JOptionPane.showInputDialog(
  97.             "Enter employee " + empNo + " commission rate: "));
  98.         employees[empNo-1] = new CommissionEmployee(first, last,
  99.             ssn, month, day, year, sales, rate);
  100.        }
  101.  
  102.  
  103.        else if(workerType.equalsIgnoreCase("Base Plus Commission")){ 
  104.         first=JOptionPane.showInputDialog("Enter employee " + empNo + 
  105.               " first name: ");
  106.         last=JOptionPane.showInputDialog("Enter employee " + empNo +
  107.               " last name: ");
  108.         ssn=JOptionPane.showInputDialog(
  109.             "Enter employee " + empNo + " ssn: ");
  110.         month=Integer.parseInt(JOptionPane.showInputDialog(
  111.             "Enter employee " + empNo + " birth month(1-12): "));
  112.         day=Integer.parseInt(JOptionPane.showInputDialog(
  113.             "Enter employee " + empNo + " birth day(1-31): "));
  114.         year=Integer.parseInt(JOptionPane.showInputDialog(
  115.             "Enter employee " + empNo + " birth year(yyyy): "));
  116.         sales=Float.parseFloat(JOptionPane.showInputDialog(
  117.             "Enter employee " + empNo + " weekly sales: "));
  118.         rate=Float.parseFloat(JOptionPane.showInputDialog(
  119.             "Enter employee " + empNo + " commission rate: "));
  120.         salary=Float.parseFloat(JOptionPane.showInputDialog(
  121.             "Enter employee " + empNo + " base salary: "));
  122.         employees[2] = 
  123.                new BasePlusCommissionEmployee(first, last, ssn, month,
  124.             day, year, sales, rate, salary);
  125.        }
  126.  
  127.  
  128.  
  129.      }
  130.  
  131.  
  132.     // initialize array with Employees
  133.       //employees[ 0 ] = new SalariedEmployee( "John", "Smith",
  134.       //   "111-11-1111", 1000, 1, 1, 1960 );
  135.       //employees[ 1 ] = new CommissionEmployee( "Sue", "Jones",
  136.       //   "222-22-2222", 12000, .05, 2, 1, 1962 );
  137.       //employees[ 2 ] = new BasePlusCommissionEmployee( "Bob", "Lewis",
  138.       //   "333-33-3333", 10000, .03, 500, 3, 1, 1963 );
  139.       //employees[ 3 ] = new HourlyEmployee( "Karen", "Price",
  140.       //   "444-44-4444", 20., 40, 4, 1, 1964 );
  141.       //employees[ 4 ] = new SalariedEmployee( "Bruce", "Chiesa",
  142.       //   "555-55-5555", 1000, 11, 1, 1961 );
  143.  
  144.         String output ="";
  145.  
  146.         for(int i=1; i<employees.length+1; i++){
  147.            output += employees[i-1].toString();
  148.  
  149.          // determine whether element is a BasePlusCommissionEmployee
  150.          if ( employees[ i-1 ] instanceof BasePlusCommissionEmployee ) {
  151.  
  152.             // downcast Employee reference to
  153.             // BasePlusCommissionEmployee reference
  154.             BasePlusCommissionEmployee currentEmployee =
  155.                ( BasePlusCommissionEmployee ) employees[ i-1 ];
  156.  
  157.             double oldBaseSalary = currentEmployee.getBaseSalary();
  158.             output += "\nold base salary: $" + oldBaseSalary;
  159.  
  160.             currentEmployee.setBaseSalary( 1.10 * oldBaseSalary );
  161.             output += "\nnew base salary with 10% increase is: $" +
  162.                currentEmployee.getBaseSalary();
  163.  
  164.          } // end if
  165.  
  166.          output += "\nearned $" + employees[ i-1 ].earnings()*4 + "\n";
  167.  
  168.       } // end for
  169.  
  170.       // get type name of each object in employees array
  171.       for ( int j = 1; j < employees.length+1; j++ )
  172.          output += "\nEmployee " + j + " is a " +
  173.             employees[ j-1 ].getClass().getName();
  174.  
  175.       JOptionPane.showMessageDialog( null, output );  // display output
  176.       System.exit( 0 );
  177.  
  178.    } // end main
  179.  
  180. } // end class PayrollSystemTest
  181.  
  182.  
error is on this line on 148
Expand|Select|Wrap|Line Numbers
  1. output += employees[i-1].toString();
May 4 '08 #1
3 2588
Laharl
849 Recognized Expert Contributor
i goes from 1 to employees.lengt h+1, so i-1 goes from 0->employees.leng th. However, because arrays are zero-indexed, employees[employees.lengt h] is the employees.lengt h+1'th item. Thus, you're outside your array. Quite frankly, I'm surprised you got a NullPointerExce ption, as you should probably have gotten an ArrayIndexOutOf BoundsException first when it tries to resolve the element.
May 4 '08 #2
gator6688
63 New Member
How do I fix it? Do I make i=0?
May 4 '08 #3
JosAH
11,448 Recognized Expert MVP
How do I fix it? Do I make i=0?
See if there are actual employees in your array:

Expand|Select|Wrap|Line Numbers
  1. for (int i= 0; i < employees.length; i++)
  2.    System.out.println(i+": "+employees[i]);
  3.  
If there is an employee present at slot i something will be printed, otherwise just
'null' will be printed. You attempt to override the toString() methond so something
sensible should be printed if an employee is printed.

Als note how the little loop above iterates over the array, i.e. there is no need to
start from 1 and subtract one from the index value again in the body of the loop.

kind regards,

Jos
May 4 '08 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

1
9124
by: Andy Howells | last post by:
Can anybody help me on this? I am getting the below error but have not got a clue why. The file in my classpath eing used has the class that it says is not defined. Any ideas? I am running java version 1.4.0 and WMQ Series version 5.3 with CSD04. Exception in thread "main" java.lang.NoClassDefFoundError: com/ibm/mq/server/MQSESSION at com.ibm.mq.MQSESSIONServer.getMQSESSION(MQSESSIONServer.java:67) at...
1
1790
by: GHKASHYAP | last post by:
Hi this is the exception i am getting when i am trying to run this application: Exception in thread "main" java.lang.NullPointerException thanks in advance.. package com.inventive.StockMarketTrading; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent;
4
14734
by: jmitch89 | last post by:
I don't why I get this error: Exception in thread "main" java.lang.NoClassDefFoundError The statement below works just fine: java -cp "appframework-1.0.3.jar;swing-worker-1.1.jar";CurrentStrobe.jar com.visionpro.currentstrobe.CurrentStrobeApp However, the statement below produces the error: java -cp "appframework-1.0.3.jar;swing-worker-1.1.jar" -jar CurrentStrobe.jar Exception in thread "main"...
3
7661
by: ohadr | last post by:
hi, i get Exception in thread "main" java.lang.NullPointerException when i run my application. the exact error is: "Exception in thread "main" java.lang.NullPointerException at sortmergejoin.MergeJoin.Field(MergeJoin.java:204) at sortmergejoin.MergeJoin.SMJoin(MergeJoin.java:84) at sortmergejoin.MergeJoin.<init>(MergeJoin.java:34) at sortmergejoin.Main.main(Main.java:24) Java Result: 1"
1
6758
by: onlinegear | last post by:
HI i am writing this for college i know i have loads of combo boxes with nothing in the i havent got that far yet. but every time i run this is comes up with this erro run: Exception in thread "main" java.lang.NullPointerException at java.awt.Container.addImpl(Container.java:1041) at java.awt.Container.add(Container.java:365) at orderingsystem.OrderingSystem.<init>(OrderingSystem.java:261) at...
0
9669
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10426
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10207
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10154
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9029
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6776
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5430
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4109
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2913
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.