473,387 Members | 1,512 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Null Pointer Exception

38
Can someone look at this with a new set of eyes and see what I am missing.
I am new to Java and this is kicking my tail.
This is a simple inventory application. I am using an array to store the variables in the Compactdisk class, and sort on the name when done.
I implimented a sub class to that named CdwArtist class since I had never done it before. (I wanted to see inheritance in action)
I have my array now using the CdwAction class like I should, everything compiles fine, but when I run it I get a NullPointerException when I enter STOP and exit my loop.
It looks to me as if I am missing something with my array, possibly crossing the name and the artist somehow, but I have stared at this so long it is just looking like garbage to me. Any help would be welcome.
Inventory class
Expand|Select|Wrap|Line Numbers
  1. import java.util.*;
  2.  
  3. public class Inventory 
  4. {// begin class Inventory
  5.  
  6.  public static int maxlength = 0;
  7.   public static CdwArtist[] sort(CdwArtist[] cds)
  8.    { 
  9.     Arrays.sort(cds, 0, maxlength); 
  10.     return cds;
  11.     }
  12.  
  13.  public static String toString(CdwArtist[] cds)
  14.   { 
  15.       String toSend = "\n\n"; 
  16.  
  17.     for(int i = 0; i < maxlength; i ++)
  18.     toSend = toSend + cds[i].getName() + "\n";
  19.     return toSend;
  20.   } 
  21.  
  22.   public static void main(String[] args)
  23.   {//begin method main
  24.  
  25.    // create cd Array 
  26.     CdwArtist[] cds = new CdwArtist[100];
  27.  
  28.  
  29.     float totalValue = 0; 
  30.  
  31.     Scanner input = new Scanner(System.in); // create scanner 
  32.  
  33.     // begin display method 
  34.     System.out.print("Enter up to 99 CD Names or STOP to Exit: "); 
  35.     String nameInput = input.nextLine(); //read cd name 
  36.  
  37.     maxlength ++; 
  38.  
  39.      for(int i = 1; i < cds.length && !nameInput.equalsIgnoreCase("STOP"); i++)
  40.      {// begin main While
  41.       cds[i] = new CdwArtist();
  42.       cds[i].setName(nameInput);
  43.  
  44.       System.out.print("Enter CD Artist Name: "); // prompt for artist name
  45.       CdwArtist artist = new CdwArtist(input.nextLine()); 
  46.  
  47.       System.out.print("Enter Price of this CD: "); // prompt for price
  48.       cds[i].setPrice(input.nextFloat()); // price input from user. 
  49.       while (cds[i].getPrice()<= 0) 
  50.          {// begin while 
  51.            System.out.print("Price Must Be Greater Than Zero. Enter Price: ");
  52.             cds[i].setPrice(input.nextFloat()); // cd price loop from user.
  53.           } // End while 
  54.  
  55.       System.out.print("Enter CD Item Number: "); // prompt for cd item number
  56.       cds[i].setItemno(input.nextInt()); // cds item number input from user 
  57.  
  58.       System.out.print("Enter Number of these CDs in Stock: "); // prompt for cd stock 
  59.       cds[i].setNstock(input.nextInt()); // cds in stock input from user
  60.  
  61.       System.out.print("\n\nCD "+cds[i].getName()+", Item Number "+cds[i].getItemno()+","); // display name 
  62.       System.out.printf(" is worth %c%.2f.",'$', + cds[i].getPrice());//
  63.       System.out.print("\nWe have "+ cds[i].getNstock()+" copies in stock,");
  64.       System.out.printf(" making our inventory for this cd worth %c%.2f.\n", '$', + cds[i].getValue()); //inventory value 
  65.  
  66.       if(cds[i].getValue() != -1) totalValue = totalValue + cds[i].getValue();
  67.       System.out.printf("Combined Inventory for all CDs is Worth %c%.2f.\n\n\n", '$', + totalValue);
  68.  
  69.       System.out.print("Enter up to 99 CD Names or STOP to Exit: "); 
  70.       input=new Scanner(System.in); // internal loop prompt 
  71.       nameInput = input.nextLine(); //name input from user 
  72.  
  73.       maxlength ++; 
  74.       } // End main While
  75.  
  76.        //System.out.println(toString(cds));
  77.         System.out.println(toString(sort(cds))); 
  78.         System.out.print("Ending Program."); 
  79.  
  80.    }// end method main 
  81. } // end class Payroll
  82.  
then the compactdisk class I first set up (even though this should require no modification at all to impliment a subclass.
Expand|Select|Wrap|Line Numbers
  1. import java.lang.Comparable;
  2.  
  3. public class Compactdisk implements Comparable
  4. {// begin class
  5.  
  6.     //InventoryCD class has 5 fields
  7.     private String name; //  Name of cd
  8.     private float price; // price of cd
  9.     private int itemno; // item number of cd
  10.     private int nstock; // how many units in stock    
  11.     private int i; // cd counter for array
  12.     private float value; // value for single cd inventory
  13.  
  14.  
  15.     //Compact disk class constructor
  16.     public Compactdisk()
  17.  
  18.         // 4 fields need to be set up
  19.         { 
  20.         name = "";
  21.         price = 0;
  22.         itemno = 0;
  23.         nstock = 0;
  24.         i = 0;
  25.         value = 0;
  26.         }
  27.  
  28.         // set values
  29.        public void setName(String diskName)
  30.        {
  31.        name = diskName;
  32.        }
  33.         public void setPrice(float cdPrice)
  34.        {
  35.        price = cdPrice;
  36.        }
  37.         public void setItemno(int cdItemno)
  38.        {
  39.        itemno = cdItemno;
  40.        }
  41.          public void setNstock(int cdStock)
  42.        {
  43.        nstock = cdStock;
  44.        }
  45.         public void setValue(float cdValue)
  46.         {
  47.         value = cdValue;
  48.         }
  49.         public void seti(int Count)
  50.         {
  51.         i = Count;
  52.         }
  53.  
  54.  
  55.        // return values
  56.         public String getName()
  57.         {    
  58.         return (name);
  59.         }
  60.         public float getPrice()
  61.         {    
  62.         return (price);
  63.         }
  64.         public int getItemno()
  65.         {    
  66.         return (itemno);
  67.         }
  68.         public int getNstock()
  69.         {    
  70.         return (nstock);
  71.         }
  72.         public int compareTo(Object in)
  73.        {
  74.        return ((Comparable)name.toLowerCase()).compareTo((Comparable)((Compactdisk)in).getName().toLowerCase());
  75.        }
  76.  
  77.         // returns indivudual inventory value for a disk
  78.        public float getValue()
  79.        {
  80.        return(price * nstock);
  81.        }
  82.  
  83.  
  84.  
  85.  
  86.  
  87. }// end class
  88.  
and then my new subclass. everything worked fine before I did this.
Expand|Select|Wrap|Line Numbers
  1. import java.util.*;
  2.  
  3. public class CdwArtist extends Compactdisk
  4. {
  5.  
  6.     // CdwArtist class adds one field 
  7.   public String artist; // artist performing on cd
  8.  
  9.  // Artist constructor
  10.   public CdwArtist()
  11.   {
  12.   artist = "";
  13.   }
  14.  
  15.     public CdwArtist(String in)
  16.     {
  17.     artist=in;
  18.     }
  19.  
  20.     // get value
  21.     public void setArtist(String in)
  22.     {
  23.     artist=in;
  24.     }
  25.  
  26.     // return value
  27.     public String getArtist()
  28.     {
  29.     return (artist);
  30.     }
  31.  
  32. } //End Class
Anyone?
Jul 20 '07 #1
2 1308
your Inventory class in line 77 is cause of this Exception *-*
because if you enter string "Stop" for loop in line 39 is over and line 77 will be execute but on this step method toString is call but in for loop of this method
cds[i] (when you enter "Stop" the last element of this array doesn't create ) call getName() although it element haven't instant of CdwArtist. this cause make NullPointerException

sorry about my english T-T . i'm afraid you don't understand that i explain, on this link i uploaded every class that i resolve it (little code) for ignore this exception :)

http://www.mediafire.com/?6wdlhknndxd
Jul 20 '07 #2
no1zson
38
Actually, the problem was with my array. Line 39.

for(int i = 1; i < cds.length && !nameInput.equalsIgnoreCase("STOP"); i++)

needed to be changed to

for(int i = 0; i < cds.length && !nameInput.equalsIgnoreCase("STOP"); i++)

thanks anyways though. I appreciate the effort.
Jul 20 '07 #3

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

Similar topics

102
by: junky_fellow | last post by:
Can 0x0 be a valid virtual address in the address space of an application ? If it is valid, then the location pointed by a NULL pointer is also valid and application should not receive "SIGSEGV"...
5
by: Boniek | last post by:
Hi I define a public property in a new form and I can see this property in table of Properties in Visual. How I can hide this property to see only in code ? Thank's Boniek
5
by: Tony Cheng | last post by:
for (int i=0; i<_request.Form.Count; i++ ) { string key = _request.Form.GetKey(i); if ( !key.Equals("formCode") && !key.Equals("formLanguage") && !key.Equals("__VIEWSTATE") &&...
69
by: fieldfallow | last post by:
Hello all, Before stating my question, I should mention that I'm fairly new to C. Now, I attempted a small demo that prints out the values of C's numeric types, both uninitialised and after...
18
by: Denis Petronenko | last post by:
Hello, in the following code i have segmentaion fault instead of exception. Why? What i must to do to catch exceptions in such situation? Used compiler: gcc version 3.3.6 (Debian 1:3.3.6-13) ...
3
by: Michael | last post by:
Hi, Could you tell me how to under the following statements? Does it mean each and every memory allocation will check all the pointer no matter a null pointer or not? Right? Thanks in advance! ...
1
by: zahidkhan | last post by:
Hi All, Plz help me if you can..... I have a program something like this int main(int argc,char* argv) { try { int* p = NULL;
46
by: lovecreatesbea... | last post by:
Do you prefer malloc or calloc? p = malloc(size); Which of the following two is right to get same storage same as the above call? p = calloc(1, size); p = calloc(size, 1);
76
by: valentin tihomirov | last post by:
As explained in "Using pointers vs. references" http://groups.google.ee/group/borland.public.delphi.objectpascal/browse_thread/thread/683c30f161fc1e9c/ab294c7b02e8faca#ab294c7b02e8faca , the...
18
by: sanjay | last post by:
Hi, I have a doubt about passing values to a function accepting string. ====================================== #include <iostream> using namespace std; int main() {
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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...

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.