473,804 Members | 3,088 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

java.lang.NullP ointerException error

sammyboy78
21 New Member
Hello again,
This time I'm creating a program that creates an array of CD objects and then displays the information. I've created a CD class, a CDInventory class and then a CDInventoryDisp lay to use the previos two. I've gotten all of this code oto compile but I'm still doing something wrong. I'm about to pull my hair out! When I run my CDInventoryDisp lay program it comes back with this error:

C:\Documents and Settings\Sam>ja va CDInventoryDisp lay
Exception in thread "main" java.lang.NullP ointerException
at CDInventory.cal culateInventory Value(CDInvento ry.java:35)
at CDInventoryDisp lay.main(CDInve ntoryDisplay.ja va:11)


Here are my codes:

Expand|Select|Wrap|Line Numbers
  1. // CD class
  2. // represents a compact disc
  3.  
  4. public class CD
  5. {
  6.     private String title; // CD title (name of product)
  7.     private String number; // CD product number
  8.     private int numStock; // CD stock number
  9.     private double price; // price of CD
  10.  
  11.     // constructor initializes CD information
  12.     public CD( String cdTitle, String productNumber, int numberInStock, double cdPrice )
  13.     {
  14.         title = cdTitle;
  15.         number = productNumber;
  16.         numStock = numberInStock;
  17.         price = cdPrice;
  18.  
  19.     } // end constructor
  20.  
  21.     public String toString()
  22.     {
  23.         return title + number + numStock + price;
  24.     } // end method toString
  25.  
  26. } // end class CD
Expand|Select|Wrap|Line Numbers
  1. // CDInventory.java
  2. // an inventory of CDs
  3.  
  4. public class CDInventory
  5. {
  6.     private CD compactDiscs[]; //declaration of an array of CD objects
  7.     private double inventoryValue;
  8.     private String titles[];
  9.     private String productNumbers[];
  10.     private int stockAmounts[];
  11.     private double prices[];
  12.  
  13.     public CDInventory()//constructor fills CD inventory
  14.     {
  15.         String titles[] = { "Sixpence None the Richer" , "Clear" , "NewsBoys: Love Liberty Disco" , "Skillet: Hey You, I Love Your Soul" , "Michael Sweet: Real"};
  16.         String productNumbers[] = { "D121401" , "D126413" , "2438-51720-2" , "D122966" , "020831-1376-204" };
  17.         int stockAmounts[] = { 12, 15 , 7, 10, 9 };
  18.         double prices[] = {11.99 , 9.99 , 12.99 , 10.99 , 9.99};
  19.  
  20.         compactDiscs = new CD[ 5 ]; // creation of an array of CD objects
  21.  
  22.         for (int count = 0; count < compactDiscs.length; count++ ) // populate inventory with CD objects
  23.         {
  24.             compactDiscs[ count ] = new CD( titles[ count ], productNumbers[ count ], stockAmounts[ count ], prices[ count ] );
  25.         }// end for
  26.  
  27.     } // end CDInventory constructor
  28.  
  29.     public void calculateInventoryValue( )
  30.     {
  31.         double total = 0.00;
  32.  
  33.         for ( int count = 0; count < compactDiscs.length; count++ )
  34.         {
  35.             total += stockAmounts[ count ] *  prices[ count ];
  36.  
  37.         } // end for
  38.  
  39.         inventoryValue = total;
  40.  
  41.     } //end calculateInventoryValue
  42.  
  43.     public double getInventoryValue()
  44.     {
  45.         return inventoryValue;
  46.  
  47.     } //end getInventoryValue
  48.  
  49.     public void toBuildString()
  50.     {
  51.         for( int count = 0; count < compactDiscs.length; count++ )
  52.         {
  53.             System.out.printf( "%s%-34s%-16d%-11f%-22f\n", titles[ count ], productNumbers[ count ], stockAmounts[ count ], prices[ count ] );
  54.         }// end for
  55.  
  56.  
  57.     } // end method toBuildString
  58.  
  59.  
  60. }// end class
Expand|Select|Wrap|Line Numbers
  1. // CDInventoryDisplay.java
  2. // inventory display application
  3.  
  4. public class CDInventoryDisplay
  5. {
  6.     // execute application
  7.     public static void main( String args[] )
  8.     {
  9.         CDInventory myCDInventory = new CDInventory();
  10.  
  11.         myCDInventory.calculateInventoryValue();
  12.  
  13.         System.out.printf( "%-34s%-16s%-16s%-15s", "Title", "Product Number" , "Amount in Stock" , "Item Price" );
  14.  
  15.         System.out.printf( "%s%.2f" , "The total value of the inventory is: $", myCDInventory.getInventoryValue() );
  16.  
  17.     } // end main
  18.  
  19. } // end class
Jun 16 '07 #1
3 3593
r035198x
13,262 MVP
A nullpointer exception is thrown when you try to dereference a variable pointing to null. In your method that is throwing this exception, you have three arrays that you are dereferencing. So one of them is null at the time of call. However, the jre has also given you the line number where the nullpointer was thrown. So if you look at your code at that line number, you can tell which array was null. This is how you should be removing errors/exceptions from your programs. The compiler or the jre always tries to give you the exact line number of the problem.
Jun 16 '07 #2
sammyboy78
21 New Member
A nullpointer exception is thrown when you try to dereference a variable pointing to null. In your method that is throwing this exception, you have three arrays that you are dereferencing. So one of them is null at the time of call. However, the jre has also given you the line number where the nullpointer was thrown. So if you look at your code at that line number, you can tell which array was null. This is how you should be removing errors/exceptions from your programs. The compiler or the jre always tries to give you the exact line number of the problem.

Yeah, I had been working on line 35 for a couple of hours. I just don't know what to try anymore and I'm not sure what dereferencing is, I don't think I've gotten that far in my textbook yet. I don't understand why the arrays are null since they're getting initialized with values in the constructor. I'm only here because I can't find the answers in my textbook and I've already spent hours trying to fix the problems myself.

Be gentle, I'm only 5 weeks old...
Jun 16 '07 #3
JosAH
11,448 Recognized Expert MVP
I don't understand why the arrays are null since they're getting initialized with values in the constructor.
No they're not: you defined a couple of variables local to the constructor again
and you initialized those instead of your member array variables. In other words:
your member array variables are still null which explains the exception that was
thrown at you.

kind regards,

Jos
Jun 16 '07 #4

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

Similar topics

1
3112
by: Jens Mueller | last post by:
Hi there, this is a Java-XML Question, so I am not sure whether this is the right place, haven't found anything better .... I try to convert a Java object to XML via SAX and let the FOP Transformer convert that via XSLT to valid XSL-FO. So I define a SAXReader which fires the SAX Events for the Java Object. This works fine and the Transformation to PDF is ok. However, I have one object which contains an XHTML String and the tags
2
13522
by: Tim Murray | last post by:
First of all, I don't know much about Java, even its naming and version numbering nomenclature, and second, if there is a better group to ask this in, please let me know. System is Mac with 10.4.4. I have Java 1.3.1 and 1.4.2 plug-ins, and J2SE 5.0 (1.5.0) installed. The Java preferences application lets me choose J2SE 5 or 1.4.2 to run applets via a browser. The problem happens in both settings. The problem is that we have a...
12
7137
nomad
by: nomad | last post by:
Hi everyone; My Class has ended and I was not able to solve this problem in time, and I would still like to solve it. I got these error code. Exception in thread "main" java.lang.NullPointerException at ticketSales.TicketSales.makeEvent(TicketSales.java:185) at ticketSales.TicketInput.main(TicketInput.java:56) Anyway I have several Class This one is called TransAction
0
1613
by: gezkk | last post by:
hi, i m using http proxy service to get proxy and host to applet, its working fine with jdk1.5 but getting java.lang.NullPointerException in jdk1.6 And the following is mseeage contains java console java.lang.NullPointerException at com.atonesoftware.web.applet.transfer.client.http.HTTPTransfer.autoDetectProxy(HTTPTransfer.java:326)
0
1650
by: ycinar | last post by:
hey all, i am working on a Java project using JBuilder.. when i build my code its fine, but when comes to run, it doesnt run and displays the following logs.. i think there is JDK conflict.. actually when i build it, it creates a jar file which is totally fine (i can confirm that because i use that jar file in another project) any idea on how to get around this? maybe i could try to run it from the command line, but dont know how to run...
1
2537
by: ketand1 | last post by:
import java.awt.*; import java.awt.event.*; import java.io.*; import java.util.*; import java.sql.*; import java.lang.*; class DbAwt extends Frame implements ActionListener { private TextField t1, t2, t3;
2
2645
by: chokcheese | last post by:
I'm having trouble with a java application. When I try and run the program it shows a java.lang.NullPointerException in the "tic.getClient().getClientTicketList().add(tic);" line (it's in bold). I know it has something to do with an object being null, but I just can't figure out which... Can anyone help? Any suggestions are greatly appreciated :) (By the way, I translated the code to english but I might have forgotten to translate a word, so if...
2
3964
by: lilyumestar | last post by:
This project is due by Tuesday and I haven't even gotten half of it done. Can anyone please help me with this Exception error? I've been trying to figure it out for several hours Error Message "Main" Java.lang NullPointerException at Project1.sortingByZipCode<Project1.java:80> at Project1.main<Project1.java:31> Here is the Source Code
3
7662
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"
0
9705
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
9575
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
10564
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
10320
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
10308
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
10073
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...
0
9134
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
6846
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();...
2
3806
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.