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: - // CD class
-
// represents a compact disc
-
-
public class CD
-
{
-
private String title; // CD title (name of product)
-
private String number; // CD product number
-
private int numStock; // CD stock number
-
private double price; // price of CD
-
-
// constructor initializes CD information
-
public CD( String cdTitle, String productNumber, int numberInStock, double cdPrice )
-
{
-
title = cdTitle;
-
number = productNumber;
-
numStock = numberInStock;
-
price = cdPrice;
-
-
} // end constructor
-
-
public String toString()
-
{
-
return title + number + numStock + price;
-
} // end method toString
-
-
} // end class CD
- // CDInventory.java
-
// an inventory of CDs
-
-
public class CDInventory
-
{
-
private CD compactDiscs[]; //declaration of an array of CD objects
-
private double inventoryValue;
-
private String titles[];
-
private String productNumbers[];
-
private int stockAmounts[];
-
private double prices[];
-
-
public CDInventory()//constructor fills CD inventory
-
{
-
String titles[] = { "Sixpence None the Richer" , "Clear" , "NewsBoys: Love Liberty Disco" , "Skillet: Hey You, I Love Your Soul" , "Michael Sweet: Real"};
-
String productNumbers[] = { "D121401" , "D126413" , "2438-51720-2" , "D122966" , "020831-1376-204" };
-
int stockAmounts[] = { 12, 15 , 7, 10, 9 };
-
double prices[] = {11.99 , 9.99 , 12.99 , 10.99 , 9.99};
-
-
compactDiscs = new CD[ 5 ]; // creation of an array of CD objects
-
-
for (int count = 0; count < compactDiscs.length; count++ ) // populate inventory with CD objects
-
{
-
compactDiscs[ count ] = new CD( titles[ count ], productNumbers[ count ], stockAmounts[ count ], prices[ count ] );
-
}// end for
-
-
} // end CDInventory constructor
-
-
public void calculateInventoryValue( )
-
{
-
double total = 0.00;
-
-
for ( int count = 0; count < compactDiscs.length; count++ )
-
{
-
total += stockAmounts[ count ] * prices[ count ];
-
-
} // end for
-
-
inventoryValue = total;
-
-
} //end calculateInventoryValue
-
-
public double getInventoryValue()
-
{
-
return inventoryValue;
-
-
} //end getInventoryValue
-
-
public void toBuildString()
-
{
-
for( int count = 0; count < compactDiscs.length; count++ )
-
{
-
System.out.printf( "%s%-34s%-16d%-11f%-22f\n", titles[ count ], productNumbers[ count ], stockAmounts[ count ], prices[ count ] );
-
}// end for
-
-
-
} // end method toBuildString
-
-
-
}// end class
- // CDInventoryDisplay.java
-
// inventory display application
-
-
public class CDInventoryDisplay
-
{
-
// execute application
-
public static void main( String args[] )
-
{
-
CDInventory myCDInventory = new CDInventory();
-
-
myCDInventory.calculateInventoryValue();
-
-
System.out.printf( "%-34s%-16s%-16s%-15s", "Title", "Product Number" , "Amount in Stock" , "Item Price" );
-
-
System.out.printf( "%s%.2f" , "The total value of the inventory is: $", myCDInventory.getInventoryValue() );
-
-
} // end main
-
-
} // end class
3 3593
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.
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...
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
Sign in to post your reply or Sign up for a free account.
Similar topics |
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
|
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...
|
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
|
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)
|
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...
| |
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;
|
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...
|
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
|
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"
|
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...
|
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,...
| |
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...
|
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...
|
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,...
|
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...
|
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...
|
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();...
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |