473,725 Members | 2,230 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 2576
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
9117
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
1784
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
14722
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
7654
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
6756
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
8749
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9252
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
9168
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
9103
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6700
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6009
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();...
1
3217
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
2
2631
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2154
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.