ArrayList problem

Well, im new to ArrayList and im having great trouble trying to figure things out,
this is what im supposed to do:
The Problem
A banking institution offers certificates of deposit (CD's) with a variety of interest rates, and maturities of 1, 3, 5, and 10 years. Interest is always compounded, daily, monthly, or quarterly.
Write a Java program that will compute the accumulated value (principal plus interest earned), at yearly intervals, of any number of such CD's. Assume that a year always consists of exactly 365 days.
Output will be a series of 10 annual reports:
Reports will be in table form with appropriate column headings. There will be one row of the table for each active CD, which will include all the data along with the accumulated value and total interest earned to data.
Each report will also print the total interest earned by all CDs for the current year, and total interest earned by all active CD�s to data.
Once a CD reaches maturity, it will stop earning interest and will not appear in any future reports. E.g., a CD with a maturity of 5 years will appear in the reports for years one through five, but not thereafter.
The CD Class
Begin by creating a class to model a CD. Each CD object "knows" its own principal, interest rate, maturity, and compounding mode (private instance variables). The class has �get� methods to return this data and a method to compute and return the accumulated value.
The CDList Class
Now create a class to maintain a list of CDs. You will need methods to add a CD to the list and to print the annual report.
The Driver (i.e., "Test") Class
Your test class or "driver" class will read data for any number of CDs from a file that I will supply. Each line of the file will contain the data � principal, interest rate (as an annual per cent), maturity, and compounding mode � for one CD.
First, tokenize each line read, create a CD object from the tokens, and add it to the list. Then print the reports.
Additional Specifications
Your CDList class must use an ArrayList as the principal (no pun intended) data structure.
Your test class is to read the data file one time only. No credit will be given for programs that read the data file more than once.
Make sure your program is well documented and adheres to the style conventions discussed in class.
Due date:          Thursday, April 20th
Formula
The accumulated value (i.e., principal plus interest), A, is given by the formula:
                                             r nt
               A = p ( 1 + ���� )
                                             n
               where
p = principal
n = number of times compounded per year
r = annual interest rate, expressed as a decimal
t = elapsed time in years
now, im supposed to read data from a file, and whats inside the file is:
5000 5 8.25 quarterly
12000 10 10.80 daily
2000 5 7.30 quarterly
10000 3 5.55 monthly
2000 1 4.50 daily
5000 10 9.15 monthly
now, im totally lost, however, ive managed to do this so far:
import java.util.ArrayList;
import java.io.*;
import java.util.*;
class CD
     private String time;     
     private double cdAmount;
     private int cdMonths;
     private double cdInterest;
     public CD(String time, double cdAmount, int cdMonths, double cdInterest)
          this.time = time;
          this.cdAmount = cdAmount;
          this.cdMonths = cdMonths;
          this.cdInterest = cdInterest;     
     public String getTime()
          return time;
     public double CDAmount()
          return cdAmount;
     public int CDMonths()
          return cdMonths;
     public double CDInterest()
          return cdInterest;
class CDlist
     private ArrayList<CD> list;
     public CDlist()
          list = new ArrayList<CD>();
     public void addList(CD info)
          list.add(info);
     }Please any help regarding this subject will be greatly appreciated.

Ok, lets take this step by step,
it says that in the cd class im supposed to have:
Each CD object "knows" its own principal, interest rate, maturity, and compounding mode (private instance variables)"
1. i have 4 variables, am i missing something in the CD class?
2. the cdlist class is supposed to have this:
"Now create a class to maintain a list of CDs. You will need methods to add a CD to the list and to print the annual report."
i have created an empty list, do i need to add the 4 variables into the list ive created??
3. the test class says this:
"Your test class or "driver" class will read data for any number of CDs from a file that I will supply. Each line of the file will contain the data � principal, interest rate (as an annual per cent), maturity, and compounding mode � for one CD.
First, tokenize each line read, create a CD object from the tokens, and add it to the list. Then print the reports."
well i dont know how to do this, but ill try not to worry about this now

Similar Messages

  • ArrayList() problems

    Hi!
    I need a little help getting an ArrayList to work. I am refactoring some of the classes in one of the O'Reilly books for a class assignment. I believe that I cannot get my ArrayList to add elements into itself. I'm not quite sure what I'm doing wrong. I'll post the code below. The problem arises in the last part of the code (at least I think it does) where i can't get my variable "size" (see the "for loop" below) to be resolved. I have tried initializing the variable at the beginning of the entire class in which case I can get the file to compile to a class. But when I run the class, I still get an ArrayOutOfBounds exception letting me know that my array is still initialized to 1 when i believe that and my index is a larger number (the number I input into the console). the message I get from the command line is:
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    Error:
    java.lang.ArrayIndexOutOfBoundsException: -1
    at java.util.ArrayList.get(ArrayList.java:326)
    at MyFactorial.computeFactorialCacheB(MyFactorial.java:115) // this would be the second line of the "for" loop
    at MyFactorial.main(MyFactorial.java:134)
    Any help would be greatly appreciated. Thanks in advance.
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    Here is my code
         public static synchronized BigInteger computeFactorialCacheB(String s) {
         private static int size;
    ArrayList table = new ArrayList();
              table.add(BigInteger.valueOf(1));
              int x = 0;
              try {
                   x = Integer.parseInt(s);
              catch (NumberFormatException e) {
                   System.out.println("the number you enter must be an integer");
              if (x<0) {
                   throw new IllegalArgumentException("x must not be a negative number");     
              else {
                   for(int size = table.size(); size <= x; size++);{
                        BigInteger lastfact = (BigInteger)table.get(size-1);
                        BigInteger nextfact = lastfact.multiply(BigInteger.valueOf(size));
                        table.add(nextfact);
              return (BigInteger) table.get(size-1);
         }

    Thanks for your reply.
    As I said in my original posting, I am refactoring code from one of the O'Reilly books for an assignment. So no, this isn't all my code, just some of it (copyright is duly noted in my assignment).
    The semicolon was a great cach (thanks!) I truly didn't see it. The issue of the "size" variable is what I am trying to solve. When I originally entered the code int my IDE (eclipse) the first declaration of int size inside the for loop was OK but subsequent references to it (still in the for loop) wouldn't resolve.
         for(int size = table.size(); size <= x; size++){
               BigInteger lastfact = (BigInteger)table.get(size-1);
               BigInteger nextfact = lastfact.multiply(BigInteger.valueOf(size));
                    table.add(nextfact);Hence the experimentation with the "size" variable. The use of the ArrayList was one of the parameters of the assignment. I see what you mean by creating a new list each time. The purpose of the method is to return a factorial (n!) using a BigInteger. This loop is pretty much just as it came out of O'rilley. It seems to work fine in their rendition (I guess that's why they get to write books).
    Tanks so much for your help. I'll refactor again and repost (probably tomorrow).
    � regards!

  • ArrayList problem ....i can remove my object from my arrayList

    hi all, i am going to remove a object from my array by using arrayList.However, it can`t work properly and did nth for me..i don`t know why...could anyone give me some suggestion and show me what i did wrong on my code ....i stated more detail next to my code...plesae help...
    public class MusicCd
         private String musicCdsTitle;
            private int yearOfRelease;
         public MusicCd()
              musicCdsTitle = "";
              yearOfRelease = 1900;
         public MusicCd(String newMusicCdsTitle)
              musicCdsTitle = newMusicCdsTitle;
              //yearOfRelease = newYearOfRelease;
         public MusicCd(String newMusicCdsTitle, int newYearOfRelease)
              musicCdsTitle = newMusicCdsTitle;
              yearOfRelease = newYearOfRelease;
         public String getTitle()
              return musicCdsTitle;
         public int getYearOfRelease()
              return yearOfRelease;
         public void setTitle(String newMusicCdsTitle)
              musicCdsTitle = newMusicCdsTitle;
         public void setYearOfRelease(int newYearOfRelease)
              yearOfRelease = newYearOfRelease;
         public boolean equalsName(MusicCd otherCd)
              if(otherCd == null)
                   return false;
              else
                   return (musicCdsTitle.equals(otherCd.musicCdsTitle));
         public String toString()
              return("Music Cd`s Title: " + musicCdsTitle + "\t"
                     + "Year of release: " + yearOfRelease + "\t");
    import java.util.ArrayList;
    import java.io.*;
    public class MusicCdStore
       ArrayList<MusicCd> MusicCdList;
       public void insertCd()
            MusicCdList = new ArrayList<MusicCd>( ); 
            readOperation theRo = new readOperation();
            MusicCd theCd;
            int muiseCdsYearOfRelease;
            String muiseCdsTitle;
              while(true)
                    String continueInsertCd = "Y";
                   do
                        muiseCdsTitle = theRo.readString("Please enter your CD`s title : ");
                        muiseCdsYearOfRelease = theRo.readInt("Please enter your CD`s year of release : ");
                        MusicCdList.add(new MusicCd(muiseCdsTitle, muiseCdsYearOfRelease));
                        MusicCdList.trimToSize();
                        continueInsertCd = theRo.readString("Do you have another Cd ? (Y/N) : ");
                   }while(continueInsertCd.equals("Y") || continueInsertCd.equals("y") );
                   if(continueInsertCd.equals("N") || continueInsertCd.equals("n"));
                                                    //MusicCdList.add(new MusicCd(muiseCdsTitle, muiseCdsYearOfRelease));                              
                                  break;
                      //System.out.println("You `ve an invalid input " + continueInsertCd + " Please enter (Y/N) only!!");
       public void displayAllCd()
                    System.out.println("\nOur CD collection is: \n" );
              System.out.println(toString());
       public String toString( )
            String result= " ";
            for( MusicCd tempCd : MusicCdList)
                 result += tempCd.toString() + "\n";
            return result;
       public void searchingMusicCd()
            readOperation theRo = new readOperation();
            String keyword = theRo.readString("Enter a CD `s Title you are going to search : ") ;
            ArrayList<MusicCd> results = searchForTitle(keyword );
              System.out.println("The search results for " + keyword + " are:" );
              for(MusicCd tempCd : results)
                   System.out.println( tempCd.toString() );
       //encapsulate the A
       public void removeCd()
            readOperation theRo = new readOperation();
            String keyword = theRo.readString("Please enter CD `s title you are going to remove : ") ;
            ArrayList<MusicCd> removeMusicCdResult = new ArrayList<MusicCd>();
                  System.out.println("The CD that you just removed  is " + keyword );
              for(MusicCd tempCd : removeMusicCdResult)
                   System.out.println( tempCd.toString() );
       //problem occurs here : i am so confused of how to remove the exactly stuff from my arrayList
       //pls help
       private ArrayList<MusicCd> removeCdForTitle(String removeCdsTitle)
             MusicCd tempMusicCd = new MusicCd();
             tempMusicCd.setTitle(removeCdsTitle);
            // tempMusicCd.setTitle(removeCdsTitle);
            //tempMusicCd.getTitle() = removeCdsTitle;
            ArrayList<MusicCd> removeMusicCdResult = new ArrayList<MusicCd>();
            for(MusicCd currentMusicCd : MusicCdList)
                 if((currentMusicCd.getTitle()).equals(tempMusicCd.getTitle()))
                     // removeMusicCdResult.remove(currentMusicCd);
                         MusicCdList.remove(currentMusicCd);
            removeMusicCdResult.trimToSize();
            return removeMusicCdResult;
       private ArrayList<MusicCd> searchForTitle(String searchString)
            ArrayList<MusicCd> searchResult = new ArrayList<MusicCd>();
            for(MusicCd currentMusicCd : MusicCdList)
                 if((currentMusicCd.getTitle()).indexOf(searchString) != -1)
                      searchResult.add(currentMusicCd);
            searchResult.trimToSize();
            return searchResult;
    import java.util.*;
    public class MusicCdStoreEngine{
         public static void main(String[] args)
              MusicCdStore mcs = new MusicCdStore( );
              mcs.insertCd();
              //display the Cd that you just insert
              mcs.displayAllCd();
              mcs.removeCd();
              mcs.displayAllCd();
              mcs.searchingMusicCd();
    //Acutally result
    //Please enter your CD`s title : ivan
    //Please enter your CD`s year of release : 1992
    //Do you have another Cd ? (Y/N) : y
    //Please enter your CD`s title : hero
    //Please enter your CD`s year of release : 1992
    //Do you have another Cd ? (Y/N) : n
    //Our CD collection is:
    // Music Cd`s Title: ivan     Year of release: 1992
    //Music Cd`s Title: hero     Year of release: 1992     
    //Please enter CD `s title you are going to remove : hero
    //The CD that you just removed  is hero
    //Our CD collection is:
    // Music Cd`s Title: ivan     Year of release: 1992
    //Music Cd`s Title: hero     Year of release: 1992     
    //Enter a CD `s Title you are going to search : hero
    //The search results for hero are:
    //Music Cd`s Title: hero     Year of release: 1992
    //>Exit code: 0
    //Expected result
    //Please enter your CD`s title : ivan
    //Please enter your CD`s year of release : 1992
    //Do you have another Cd ? (Y/N) : y
    //Please enter your CD`s title : hero
    //Please enter your CD`s year of release : 1992
    //Do you have another Cd ? (Y/N) : n
    //Our CD collection is:
    // Music Cd`s Title: ivan     Year of release: 1992
    //Music Cd`s Title: hero     Year of release: 1992     
    //Please enter CD `s title you are going to remove : hero
    //The CD that you just removed  is hero
    //Our CD collection is:
    // Music Cd`s Title: ivan     Year of release: 1992
    //Music Cd`s Title: hero     Year of release: 1992<<-- it is not supposed to display cos i have deleted it from from array     
    //Enter a CD `s Title you are going to search : hero
    //The search results for hero are:
    //Music Cd`s Title: hero     Year of release: 1992<<-- i should have get this reuslt...cos it is already delete from my array
    //>Exit code: 0
    import java.util.*;
    public class readOperation{
         public String readString(String userInstruction)
              String aString = null;
              try
                         Scanner scan = new Scanner(System.in);
                   System.out.print(userInstruction);
                   aString = scan.nextLine();
              catch (NoSuchElementException e)
                   //if no line was found
                   System.out.println("\nNoSuchElementException error occurred (no line was found) " + e);
              catch (IllegalStateException e)
                   // if this scanner is closed
                   System.out.println("\nIllegalStateException error occurred (scanner is closed)" + e);
              return aString;
         public char readTheFirstChar(String userInstruction)
              char aChar = ' ';
              String strSelection = null;
              try
                   //char charSelection;
                         Scanner scan = new Scanner(System.in);
                   System.out.print(userInstruction);
                   strSelection = scan.next();
                   aChar =  strSelection.charAt(0);
              catch (NoSuchElementException e)
                   //if no line was found
                   System.out.println("\nNoSuchElementException error occurred (no line was found) " + e);
              catch (IllegalStateException e)
                   // if this scanner is closed
                   System.out.println("\nIllegalStateException error occurred (scanner is closed)" + e);
              return aChar;
         public int readInt(String userInstruction) {
              int aInt = 0;
              try {
                   Scanner scan = new Scanner(System.in);
                   System.out.print(userInstruction);
                   aInt = scan.nextInt();
              } catch (InputMismatchException e) {
                   System.out.println("\nInputMismatchException error occurred (the next token does not match the Integer regular expression, or is out of range) " + e);
              } catch (NoSuchElementException e) {
                   System.out.println("\nNoSuchElementException error occurred (input is exhausted)" + e);
              } catch (IllegalStateException e) {
                   System.out.println("\nIllegalStateException error occurred (scanner is closed)" + e);
              return aInt;
    }

    //problem occurs hereI'm not sure that the problem does occur within the
    removeCdForTitle() method.
    Your main() method calls removeCd() which obtains the title of
    the CD to be removed (keyword). But remoceCd() never
    calls removeCdForTitle(), so nothing is ever removed.

  • Reading into ArrayList problem - what is wrong?

    Hi, I am trying to read a list of strings into an ArrayList and am having some problems. I have created a main() which at the moment does nothing, its just to make sure that the array's content is genuine (meaning consistent with the string in the text file) so I am having it simply printed out to screen. The error I am getting is "cannot resolve symbol, variable array" by my compiler (Jcreator). I will paste the code below:
    import java.io.*;
    import java.util.*;
    public class hostList{
    public hostList()
    try
    File input = new File("hosts.txt");
    BufferedReader in=new BufferedReader(
         new InputStreamReader(new FileInputStream(input)));
         ArrayList list=new ArrayList();
         String line;
         while((line=in.readLine())!=null)
              list.add(line);
         String[] array=new String[list.size()];
         list.toArray(array);
         in.close();
    catch(FileNotFoundException e)
    System.err.println("File not found...");
    catch(IOException e)
    System.err.println("IO Problem");
    }//hostLst()
         public static void main (String [] args){
              System.out.println("Array content:");
              System.out.println("array " + array[0]);
              for (int i=0; array[i] !=null; i++)
                   System.out.println(array);
         }//main
    }//class
    Also, how would I use the array objects in another class, say class B. How can I access the arrays in class B so that i can use its methods? eg. array[i].doSomething(); where doSomething() is a method in class B. What libraries would i need to import (if any) ?
    Help is appreciated, thanks.

    this code wont compile bcas in main method u r not creating the object of this class also the var array is not globally declared hence wont be accesibile outside
    u can try this modified code
    import java.io.*;
    import java.util.*;
    public class hostList{
    String[] array=null;
    public hostList()
    try
    File input = new File("hosts.txt");
    BufferedReader in=new BufferedReader(
    new InputStreamReader(new FileInputStream(input)));
    ArrayList list=new ArrayList();
    String line;
    while((line=in.readLine())!=null)
    list.add(line);
    array=new String[list.size()];
    list.toArray(array);
    in.close();
    catch(FileNotFoundException e)
    System.err.println("File not found...");
    catch(IOException e)
    System.err.println("IO Problem");
    }//hostLst()
    public static void main (String [] args){
    hostList h=new hostList();
    System.out.println("Array content:");
    System.out.println("array " + h.array[0]);
    }//main
    }//class

  • Cannot find symbol error - ArrayList problem

    Hey guys,
    I'll post the code, and then the error message below. Essentially I'm getting an error message on the add and it's a bit confusing, since I've imported ArrayList and add is a method in there as well.
    My question: What am I missing? If someone could post what I'm missing, I'd appreciate it. No trolls please.
    import java.text.NumberFormat;
    import java.util.ArrayList;
    import java.util.Iterator;
    public class CDCollection {
        private ArrayList collection = null;
        private double    totalCost;
        //  Constructor: Creates an initially empty collection.
        public CDCollection() {
            collection = new ArrayList(100);
            totalCost = 0.0;
        //  Adds a CD to the collection, increasing the size of the
        //  collection if necessary.
        public void addCD(String title, String artist, double cost, int tracks) {
            collection.add(new CD(title, artist, cost, tracks));
            totalCost += cost;
        //  Returns a report describing the CD collection.
        public String toString() {
            NumberFormat fmt = NumberFormat.getCurrencyInstance();
            String report = "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
            report += "My CD Collection\n\n";
            report += "Number of CDs: " + collection.size() + "\n";
            report += "Total cost: " + fmt.format(totalCost) + "\n";
            if (collection.size() != 0) {
                report += "Average cost: " + fmt.format(totalCost / collection.size());
            report += "\n\nCD List:\n\n";
            report += CDCollection.createReport(collection);
            return report;
         * @param al
         * @return
        public static String createReport(ArrayList al) {
            StringBuffer sb = new StringBuffer();
            Iterator iter = al.iterator();
            while (iter.hasNext()) {
                CD aCD = (CD) iter.next();
                sb.append(aCD.toString());
                sb.append(System.getProperty("line.separator"));
            return sb.toString();
    } and the error message:
    CDCollection.java:36: cannot find symbol
    symbol: method add(CD)
    location: class java.util.ArrayList<java.lang.String>
    collection.add(new CD(title, artist, cost, tracks));
    Any help would be very appreciated folks.

    nm, figured it out, sorry guys.
    For those reading to figure out their own answer to a similar problem....
    Private ArrayList <CD> collection = null;and
    public CDCollection(){
       ArrayList <CD> collection = new ArrayList <CD> (100);

  • ArrayList problem ....how can i remove my object.

    i am going to insert a cd to the arrayList , remove a cd from the arrayList, searchTheTitle, and display it...But i stuck on my remove function...i can `t remove the data that i want from the array..pls help..
    //MusicCd enscaslaute the cd data
    public class MusicCd
         private String musicCdsTitle;
            private int yearOfRelease;
         public MusicCd()
              musicCdsTitle = "";
              yearOfRelease = 1900;
         public MusicCd(String newMusicCdsTitle)
              musicCdsTitle = newMusicCdsTitle;
              //yearOfRelease = newYearOfRelease;
         public MusicCd(String newMusicCdsTitle, int newYearOfRelease)
              musicCdsTitle = newMusicCdsTitle;
              yearOfRelease = newYearOfRelease;
         public String getTitle()
              return musicCdsTitle;
         public int getYearOfRelease()
              return yearOfRelease;
         public void setTitle(String newMusicCdsTitle)
              musicCdsTitle = newMusicCdsTitle;
         public void setYearOfRelease(int newYearOfRelease)
              yearOfRelease = newYearOfRelease;
         public boolean equalsName(MusicCd otherCd)
              if(otherCd == null)
                   return false;
              else
                   return (musicCdsTitle.equals(otherCd.musicCdsTitle));
         public String toString()
              return("Music Cd`s Title: " + musicCdsTitle + "\t"
                     + "Year of release: " + yearOfRelease + "\t");
    import java.util.ArrayList;
    import java.io.*;
    public class MusicCdStore
       ArrayList<MusicCd> MusicCdList;
       public void insertCd()
            MusicCdList = new ArrayList<MusicCd>( ); 
            readOperation theRo = new readOperation();
            MusicCd theCd;
            int muiseCdsYearOfRelease;
            String muiseCdsTitle;
              while(true)
                    String continueInsertCd = "Y";
                   do
                        muiseCdsTitle = theRo.readString("Please enter your CD`s title : ");
                        muiseCdsYearOfRelease = theRo.readInt("Please enter your CD`s year of release : ");
                        MusicCdList.add(new MusicCd(muiseCdsTitle, muiseCdsYearOfRelease));
                        MusicCdList.trimToSize();
                        continueInsertCd = theRo.readString("Do you have another Cd ? (Y/N) : ");
                   }while(continueInsertCd.equals("Y") || continueInsertCd.equals("y") );
                   if(continueInsertCd.equals("N") || continueInsertCd.equals("n"));
                                                    //MusicCdList.add(new MusicCd(muiseCdsTitle, muiseCdsYearOfRelease));                              
                                  break;
                      //System.out.println("You `ve an invalid input " + continueInsertCd + " Please enter (Y/N) only!!");
       public void displayAllCd()
                    System.out.println("\nOur CD collection is: \n" );
              System.out.println(toString());
       public String toString( )
            String result= " ";
            for( MusicCd tempCd : MusicCdList)
                 result += tempCd.toString() + "\n";
            return result;
       public void searchingMusicCd()
            readOperation theRo = new readOperation();
            String keyword = theRo.readString("Enter a CD `s Title you are going to search : ") ;
            ArrayList<MusicCd> results = searchForTitle(keyword );
              System.out.println("The search results for " + keyword + " are:" );
              for(MusicCd tempCd : results)
                   System.out.println( tempCd.toString() );
       //encapsulate the A
       public void removeCd()
            readOperation theRo = new readOperation();
            String keyword = theRo.readString("Please enter CD `s title you are going to remove : ") ;
            ArrayList<MusicCd> removeMusicCdResult =searchForRemoveCdsTitle(keyword);
                  System.out.println("The CD that you just removed  is " + keyword );
              for(MusicCd tempCd : removeMusicCdResult)
                   System.out.println( tempCd.toString() );
       private ArrayList<MusicCd> searchForTitle(String searchString)
            ArrayList<MusicCd> searchResult = new ArrayList<MusicCd>();
            for(MusicCd currentMusicCd : MusicCdList)
                 if((currentMusicCd.getTitle()).indexOf(searchString) != -1)
                      searchResult.add(currentMusicCd);
            searchResult.trimToSize();
            return searchResult;
       private ArrayList<MusicCd> searchForRemoveCdsTitle(String searchString)
            MusicCd tempCd = new MusicCd();
            tempCd.setTitle(searchString);
            ArrayList<MusicCd> removeCdsResult = new ArrayList<MusicCd>();
            for(MusicCd currentMusicCd : MusicCdList)
                 if((currentMusicCd.getTitle()).equals(tempCd.getTitle()))
                      removeCdsResult.remove(currentMusicCd);
            removeCdsResult.trimToSize();
            return removeCdsResult;
    private ArrayList<MusicCd> searchForRemoveCdsTitle(String searchString)
            ArrayList<MusicCd> removeCdsResult = new ArrayList<MusicCd>();
            for(MusicCd currentMusicCd : MusicCdList)
                 if((currentMusicCd.getTitle()).indexOf(searchString) != -1)
                      removeCdsResult.remove(currentMusicCd);
            removeCdsResult.trimToSize();
            return removeCdsResult;
    import java.util.*;
    public class readOperation{
         public String readString(String userInstruction)
              String aString = null;
              try
                         Scanner scan = new Scanner(System.in);
                   System.out.print(userInstruction);
                   aString = scan.nextLine();
              catch (NoSuchElementException e)
                   //if no line was found
                   System.out.println("\nNoSuchElementException error occurred (no line was found) " + e);
              catch (IllegalStateException e)
                   // if this scanner is closed
                   System.out.println("\nIllegalStateException error occurred (scanner is closed)" + e);
              return aString;
         public char readTheFirstChar(String userInstruction)
              char aChar = ' ';
              String strSelection = null;
              try
                   //char charSelection;
                         Scanner scan = new Scanner(System.in);
                   System.out.print(userInstruction);
                   strSelection = scan.next();
                   aChar =  strSelection.charAt(0);
              catch (NoSuchElementException e)
                   //if no line was found
                   System.out.println("\nNoSuchElementException error occurred (no line was found) " + e);
              catch (IllegalStateException e)
                   // if this scanner is closed
                   System.out.println("\nIllegalStateException error occurred (scanner is closed)" + e);
              return aChar;
         public int readInt(String userInstruction) {
              int aInt = 0;
              try {
                   Scanner scan = new Scanner(System.in);
                   System.out.print(userInstruction);
                   aInt = scan.nextInt();
              } catch (InputMismatchException e) {
                   System.out.println("\nInputMismatchException error occurred (the next token does not match the Integer regular expression, or is out of range) " + e);
              } catch (NoSuchElementException e) {
                   System.out.println("\nNoSuchElementException error occurred (input is exhausted)" + e);
              } catch (IllegalStateException e) {
                   System.out.println("\nIllegalStateException error occurred (scanner is closed)" + e);
              return aInt;
    import java.util.*;
    public class MusicCdStoreEngine{
         public static void main(String[] args)
              MusicCdStore mcs = new MusicCdStore( );
              mcs.insertCd();
              //display the Cd that you just insert
              mcs.displayAllCd();
              mcs.removeCd();
              mcs.displayAllCd();
              //mcs.searchingMusicCd();
    //Acutally result
    //Please enter your CD`s title : ivan
    //Please enter your CD`s year of release : 1992
    //Do you have another Cd ? (Y/N) : y
    //Please enter your CD`s title : hero
    //Please enter your CD`s year of release : 1992
    //Do you have another Cd ? (Y/N) : n
    //Our CD collection is:
    // Music Cd`s Title: ivan     Year of release: 1992
    //Music Cd`s Title: hero     Year of release: 1992     
    //Please enter CD `s title you are going to remove : hero
    //The CD that you just removed  is hero
    //Our CD collection is:
    // Music Cd`s Title: ivan     Year of release: 1992
    //Music Cd`s Title: hero     Year of release: 1992     
    //Enter a CD `s Title you are going to search : hero
    //The search results for hero are:
    //Music Cd`s Title: hero     Year of release: 1992
    //>Exit code: 0
    //Expected result
    //Please enter your CD`s title : ivan
    //Please enter your CD`s year of release : 1992
    //Do you have another Cd ? (Y/N) : y
    //Please enter your CD`s title : hero
    //Please enter your CD`s year of release : 1992
    //Do you have another Cd ? (Y/N) : n
    //Our CD collection is:
    // Music Cd`s Title: ivan     Year of release: 1992
    //Music Cd`s Title: hero     Year of release: 1992     
    //Please enter CD `s title you are going to remove : hero
    //The CD that you just removed  is hero
    //Our CD collection is:
    // Music Cd`s Title: ivan     Year of release: 1992
    //Music Cd`s Title: hero     Year of release: 1992<<-- it is not supposed to display cos i have deleted it from from array     
    //Enter a CD `s Title you are going to search : hero
    //The search results for hero are:
    //Music Cd`s Title: hero     Year of release: 1992<<-- i should have get this reuslt...cos it is already delete from my array
    //>Exit code: 0

    (1) searchForRemoveCdsTitle() removes rather than adds the CDs that it finds to
    the list that it returns.So searchForRemoveCdsTitle() should be:private ArrayList<MusicCd> searchForRemoveCdsTitle(String searchString)
            MusicCd tempCd = new MusicCd();
            tempCd.setTitle(searchString);
            ArrayList<MusicCd> removeCdsResult = new ArrayList<MusicCd>();
            for(MusicCd currentMusicCd : MusicCdList)
                if((currentMusicCd.getTitle()).equals(tempCd.getTitle()))
                    //removeCdsResult.remove(currentMusicCd);
                    removeCdsResult.add(currentMusicCd); // <-- changed
            removeCdsResult.trimToSize();
            return removeCdsResult;
    (2) In removeCd() you never actually remove the CDs from the array list, you just
    print them to System.outSo removeCd() should be:public void removeCd()
            readOperation theRo = new readOperation();
            String keyword = theRo.readString("Please enter CD `s title you are going to remove : ") ;
            ArrayList<MusicCd> removeMusicCdResult =searchForRemoveCdsTitle(keyword);
            System.out.println("The CD that you just removed  is " + keyword );
            for(MusicCd tempCd : removeMusicCdResult)
                //System.out.println( tempCd.toString() );
                MusicCdList.remove(tempCd); // <-- changed
        }With these changes we get:Please enter your CD`s title : ivan
    Please enter your CD`s year of release : 1234
    Do you have another Cd ? (Y/N) : y
    Please enter your CD`s title : hero
    Please enter your CD`s year of release : 4321
    Do you have another Cd ? (Y/N) : n
    Our CD collection is:
    Music Cd`s Title: ivan     Year of release: 1234     
    Music Cd`s Title: hero     Year of release: 4321     
    Please enter CD `s title you are going to remove : hero
    The CD that you just removed  is hero
    Our CD collection is:
    Music Cd`s Title: ivan     Year of release: 1234     This "works", but I can't do more than hope that it helps. Really if something is unclear about either of these points it might be more productive to ask about that.

  • A Map and ArrayList problem

    Hi all,
    I have a TreeMap that has a string as a key and an ArrayList of Integers as a value. What I'd like to do is get each of the ArrayLists, then determine for each ArrayList where the first nonzero entry is. Once I do that, I want to lump them together, so all the arrayLists with a similar first nonzero value are together. I've been working on it, and I've got my solution partially working, but at the moment for the rest I'm stumped. Here's my code, can anyone help me out?
    Thanks,
    Jezzica85
    // "chapters" is the number of indices in the ArrayList value of FrequencyTable, minus one (the last is a sum).
    // ex. one entry of the frequencyTable is:
    //     example=[0, 1, 2, 4, 7], the last index is the sum of all the others
    public void getStartingPoints( int chapters ) {
         // frequencyTable = TreeMap<String, ArrayList<Integer>>
         // This has been fully created by the time this method is called.
         // In this example, "chapters" would be 4
         for( int i = 0; i < chapters; i++ ) {
              TreeSet<String> newWords = new TreeSet<String>();
              Iterator iterator = frequencyTable.entrySet().iterator();
              while( iterator.hasNext() ) {
                   (Map.Entry) current = (Map.Entry)iterator.next();
                   String key = (String)current.getKey();
                   ArrayList<Integer> value = (ArrayList<Integer>)current.getValue();
                   // If we're dealing with the first index in the arrayList -- this part works.
                   if( i == 0 && value.get( 0 ) > 0 ) {
                        newWords.add( key );
                   // If we're dealing with any other index -- this doesn't work.
                   // What I want to do is see if all the indices from 0 to i - 1 add up to 0.
                   if( i > 0 ) {
                        int sum = 0;
                        for( int j = 0; j < i; j++ ) {
                             sum = sum + value.get( j );
                        if( sum == 0 ) {
                             newWords.add( key );
                   

    Read, re-read, then re-read your post. Couldn't understand it.
    Please explain more:
    1- You have:frequencyTable = TreeMap<String, ArrayList<Integer>>That seems to be your input structure, right?
    So what is supposed to be your resulting structure?
    A big ArrayList that will hold all integers?
    A big Set that will hold whatever?
    Else?
    2- The other input seems to be an int named chapters.
    What is the relation between this number and the frequencyTable structure?
    3- In that frequencyTable the ArrayLists contain integers.
    Are those integers the indices you are referring?
    Are those integers allways sorted in your ArrayLists?
    Are there allways at least one zero integer in your ArrayLists?

  • Retrieve data from arraylist problem

    I need some helps from u guys on this.
    1) I have an arraylist. I will compare the value in the arraylist with object A.
    2) I will compare the value in the arraylist with object B.
    3) I need to retrieve the value in the arraylist between A and B
    i.e. :
    | arraylist |
    A <-------------------------------------------------->B
    (need to retrieve this)
    Please help me. Can't figure out how to do this. Thanks!

    hi :-)
    hope this will help.
    ObjectA objectA;
    ObjectB objectB;
    * loop first the list of ObjectA then loop again list of ObjectB
    * then compare them if you want to do something
    for(Iterator iter1=objectA_List.iterator();iter1.hasNext();)
       objectA = (ObjectA)iter1.next();
       for(Iterator iter2=objectB_List.iterator();iter2.hasNext();)
         objectB = (ObjectB)iter2.next();
            if(objectA.getExampleEntry==objectB.geExampleEntry)
                //      do something like add it to arraylist etc
            else
                // do something
    }their are other ways, but this is just one of the way do it.
    regards goodluck,

  • TableSelectOne for ArrayList problem

    Hello All,
    My af:table’ value is ArrayList. The table has af:tableSelectOne. I want that by default first row will be selected. Now none of rows is selected when the page shows up. I need to click a row. I want that it be done automatically.
    Thank you,
    SNikiforov

    Hi,
    see the selectionState property of af:table
    http://www.oracle.com/technology/products/jdev/htdocs/partners/addins/exchange/jsf/doc/tagdoc/core/table.html
    Frank

  • Arraylist.add() problem

    Hi,
    I'm trying to read a CSV text file into an arraylist.
    I can read the text file fine, its just when it gets to the actual arraylist.add() part it just .. .. doesn't work. It can print the values from the CSV file no problem. I'm sure my syntax is fine, everything compiles. I've read it and double checked it and checked it again.
    It just doesn't work .. I don't know why.
    The arraylist I am trying to read into is
    ArrayList<Customer> customers = new ArrayList<Customer>();Within other parts of the program I can read in dummy data, eg
    customers.add(new Customer(01, "Jims Mowing", "16 Long Grass Street", "Thorndale", "123-4567", "[email protected]"));
    but suffice to say, yes, it is kaput.
       * READING THE CUSTOMER TEXT FILE INTO THE ARRAY LIST
      private void custFileToArray ()
        RectangleTUI results = new RectangleTUI(); // create results object
        try   
          BufferedReader inputStream = new BufferedReader(new FileReader(PATHNAME + CUSTFILE));
          System.out.println("Contents of file: " + CUSTFILE); // print heading
          String line = inputStream.readLine(); // read first line
          while (line !=null) // test for end of file (EOF)
            results.loadCustFile(line);       
            line = inputStream.readLine(); // read next line
          // close file
          inputStream.close();
        // catch any file open errors
        catch(FileNotFoundException e)
          System.out.println("Error opening file: " + CUSTFILE);
          System.exit(0);
        catch(NoSuchElementException e)
          System.out.println("ATTENTION: One or more " + CUSTFILE + " records are missing data");
        // catch any file reading errors
        catch(IOException e)
          System.out.println("Error reading from file: " + CUSTFILE);
          System.exit(0);
        System.out.println("File Reading Complete");  
      private void loadCustFile(String textLine)
        String delimiters = ","; // set tokenizer delimiter
        StringTokenizer RecordFields = new StringTokenizer(textLine,delimiters);  
        int cidNum = Integer.parseInt(RecordFields.nextToken()); // Customer ID
        System.out.println(cidNum + " Hello I am a stupid piece of code. I don't like to work properly");
        String cName = RecordFields.nextToken();   // Name
        String cAdd = RecordFields.nextToken();   // Street Address
        String cBurb = RecordFields.nextToken();   // Suburb
        String cPhone = RecordFields.nextToken();   // Phone
        String cEmail = RecordFields.nextToken();   // Email
        customers.add(new Customer(cidNum, cName, cAdd, cBurb, cPhone, cEmail));
      }

    Cowzor wrote:
    Hi,
    Cheers for the replies & the printStackTrace tip.
    The thing is it's not actually throwing up any errors or crashing. It's acting as if everything is AOK - but since it then says there's nothig in the arraylist there must be a problem ... somewhere.
    Sorry if I've mis-understood what you were saying
    Here's the dummy data I'm using just incase it's at all relevant
    200701,Jims Mowing,16 Long Grass Street,Thorndale,123-4567,[email protected]
    200702,Chevy Racers,2 Raceway Drive,Boganville,123-4567,[email protected]
    200703,Renta Dent,82 Airport Oaks Road,Airport Oaks,123-4567,[email protected]
    200704,Discount Taxis,8 Poor Place,Otara,123-4567,[email protected]
    u split contains of CSV file on basis of , (comma) and read it

  • Problem at iteration (ArrayList)

    I`e made a soft wich writes elements from an array list to a table.
         int c=0;
         for (int a=0;a<(tabela.getRowCount());a++)
              for (int b=0;b<(tabela.getColumnCount());b++){
                   tabela.setValueAt(list.get(c),a,b);
    where tabela is the Table and list is the ArrayList. This version put into each row the element from the first position of the array list (because c=0). When i run this version, there are no problems. But if I increment c at each step (to put the nex value from the arraylist to the next row) i get this error message:
    Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index: 4, Size: 4
         at java.util.ArrayList.RangeCheck(Unknown Source)
         at java.util.ArrayList.get(Unknown Source)
         at BazaDeDate.creazaTabela(BazaDeDate.java:100)
         at BazaDeDate.<init>(BazaDeDate.java:64)
         at Fereastra$6.actionPerformed(Fereastra.java:151)
         at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
         at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
         at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
         at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
         at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
         at java.awt.Component.processMouseEvent(Unknown Source)
         at javax.swing.JComponent.processMouseEvent(Unknown Source)
         at java.awt.Component.processEvent(Unknown Source)
         at java.awt.Container.processEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Window.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)
    This is how i increment c.
         int c=0;
         for (int a=0;a<(tabela.getRowCount());a++)
              for (int b=0;b<(tabela.getColumnCount());b++){
                   tabela.setValueAt(list.get(c),a,b);
    Thanks for any good suggestions.

    Really? you don't understand what "Array Index Out Of Bounds" means?
    You've tried to access something outside of your list. Don't do that.
    Figure out why your list contains fewer items than your table has slots for; or stop assuming there are enough.

  • Problem with ArrayList

    Hello,
    I am having a problem with a program I am trying to write. The idea of the program is to:
    A) read a list of movies list from a text file
    B) create an object for each movie using the information from the text file
    C) place the objects into an arrayList
    My problem is that when I check my arrayList it seems to only contain multiple copies of the first movie read from the text file. Here is my code
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.io.FileOutputStream;
    import java.io.FileNotFoundException;
    import java.util.ArrayList;
    public class MovieReader
         PrintWriter outputStream = null;
         public void readFile()
              try
                      BufferedReader in = new BufferedReader(new FileReader("movie.txt"));
                      String str;
                      while ((str = in.readLine()) != null)
                           process(str);
                      in.close();
              catch (IOException e)
                  e.printStackTrace();
         ArrayList <ValidMovie> movieList = new ArrayList<ValidMovie>();
         private void process(String line)
              String[] array = line.split("\t");
              int i = 0;
              for ( i = 0; i < array.length; i++)
                   String tempTitle = array[0];
                   String tempYear = array [1];
                   String tempRating = array [2];
                   String tempFormat = array [3];
                   ValidMovie uuj = new ValidMovie(tempTitle, tempYear, tempRating, tempFormat);
                   movieList.add(uuj);
              System.out.println("item at index 1 is:   " + movieList.get(1));
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
         private void writeFile(String [] arrayL)
              String [] arrayWrite = arrayL;
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~     
    //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
         public static void main(String[] args)
              MovieReader mv = new MovieReader();
              mv.readFile();
    //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
    }This is the code that creates an object for each movie:
    import java.io.Serializable;
    public class ValidMovie implements Serializable
         private String title;
         private String year;
         private String rating;
         private String format;
         public ValidMovie()
         public ValidMovie(String tTitle, String tYear, String tRating, String tFormat)
              title = tTitle;
              year = tYear;
              rating = tRating;
              format = tFormat;
         //Getters for title, year, rating and format
         public String getTitle ()
              return title;
         public String getYear ()
              return year;
         public String getRating ()
              return rating;
         public String getFormat ()
              return format;
         public String toString ()
              return title + "\t" + year + "\t" + rating + "\t" + format;
    }The following is what I have in the movie.txt file:
    Bamboozled     2000     2     DVD
    What Lies Beneath     2000     1.5     DVD
    Beneath the Planet of the Apes     1970     1     DVD
    You Can Count On Me     2000     3.5     Theater
    And finally this is the result when I run the code:
    item at index 1 is: Bamboozled     2000     2     DVD
    item at index 1 is: Bamboozled     2000     2     DVD
    item at index 1 is: Bamboozled     2000     2     DVD
    item at index 1 is: Bamboozled     2000     2     DVD
    I am sure that it is something simple that I am overlooking but I cannot figure it out. When I change the index in the code:
    System.out.println("item at index 1 is:   " + movieList.get(1));to 0 or 2 or 3 then result is the same, it will just show the first movie in the text file. Any help would be greatly appreciated. Thanks

    Thanks for the reply, it helped but I am now getting 4 of each of the movies after adding you suggestion. This is much better now I just need to figure out why the loop is causing the extra copies. Thanks again :)
    Item 0: Bamboozled     2000     2     DVD
    Item 1: Bamboozled     2000     2     DVD
    Item 2: Bamboozled     2000     2     DVD
    Item 3: Bamboozled     2000     2     DVD
    Item 4: What Lies Beneath     2000     1.5     DVD
    Item 5: What Lies Beneath     2000     1.5     DVD
    Item 6: What Lies Beneath     2000     1.5     DVD
    Item 7: What Lies Beneath     2000     1.5     DVD
    Item 8: Beneath the Planet of the Apes     1970     1     DVD
    Item 9: Beneath the Planet of the Apes     1970     1     DVD
    Item 10: Beneath the Planet of the Apes     1970     1     DVD
    Item 11: Beneath the Planet of the Apes     1970     1     DVD
    Item 12: You Can Count On Me     2000     3.5     Theater
    Item 13: You Can Count On Me     2000     3.5     Theater
    Item 14: You Can Count On Me     2000     3.5     Theater
    Item 15: You Can Count On Me     2000     3.5     Theater

  • Problem in fetching values from Java Web Service returning ArrayList

    Hi all,
    I am calling an External Java web Service from BPEL. That Java Web Service is returning an Arraylist.
    I am not able to assign the values returned by the Java web service to local String Variables of BPEL.
    Kindly help me...

    Hi,
    My problem has been resolved..
    I have used
    bpws:getVariableData('Invoke_1_useSSH_OutputVariable','parameters',concat('/ns7:useSSHResponseElement/ns7:result/ns8:item\[',bpws:getVariableData('count'),']'))
    where count is the local int variable which contains the index value of the arraylist i.e. which index element we want to retrieve from arraylist.
    Thanks....
    Edited by: user643533 on Sep 12, 2008 12:10 AM

  • Problem with ArrayLists and writing and reading from a .dat file (I think)

    I'm brand new to this forum, but I'm sure hoping someone can help me with a problem I'm having with ArrayLists. This program was originally created with an array of objects that were displayed on a GUI with jtextFields, then cycling thru them via jButtons: First, Next, Previous, Last. Now I need to add the ability to modify, delete and add records. Both iterations of this program needed to write to and read from a .dat file.
    It worked just like it was suppose to when I used just the array, but now I need to use a "dynamic array" that will grow or shrink as needed: i.e. an ArrayList.
    When I aded the ArrayList I had the ArrayList use toArray() to fill my original array so I could continue to use all the methods I'd created for using with my array. Now I'm getting a nullPointerException every time I try to run my program, which means somewhere I'm NOT filling my array ???? But, I'm writing just fine to my .dat file, which is confusing me to no end!
    It's a long program, and I apologize for the length, but here it is. There are also 2 class files, a parent and 1 child below Inventory6. This was written in NetBeans IDE 5.5.1.
    Thank you in advance for any help anyone can give me!
    LabyBC
    package my.Inventory6;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.text.DecimalFormat;
    import javax.swing.JOptionPane;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JTextField;
    import java.io.*;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.lang.IllegalStateException;
    import java.util.NoSuchElementException;
    import java.util.ArrayList;
    import java.text.NumberFormat;
    // Class Inventory6
    public class Inventory6 extends javax.swing.JFrame {
    private static InventoryPlusColor[] inventory;
    private static ArrayList inList;
    // create a tool that insure the specified format for a double number, when displayed
    private DecimalFormat doubleFormat = new DecimalFormat( "0.00" );
    private DecimalFormat singleFormat = new DecimalFormat( "0");
    // the index within the array of products of the current displayed product
    private int currentProductIndex;
    /** Creates new form Inventory6 */
    public Inventory6() {
    initComponents();
    currentProductIndex = 0;
    } // end Inventory6()
    private static InventoryPlusColor[] getInventory() {
    ArrayList<InventoryPlusColor> inList = new ArrayList<InventoryPlusColor>();
    inList.add(new InventoryPlusColor(1, "Couch", 3, 1250.00, "Blue"));
    inList.add(new InventoryPlusColor(2, "Recliner", 10, 525.00, "Green"));
    inList.add(new InventoryPlusColor(3, "Chair", 6, 125.00, "Mahogany"));
    inList.add(new InventoryPlusColor(4, "Pedestal Table", 2, 4598.00, "Oak"));
    inList.add(new InventoryPlusColor(5, "Sleeper Sofa", 4, 850.00, "Yellow"));
    inList.add(new InventoryPlusColor(6, "Rocking Chair", 2, 459.00, "Tweed"));
    inList.add(new InventoryPlusColor(7, "Couch", 4, 990.00, "Red"));
    inList.add(new InventoryPlusColor(8, "Chair", 12, 54.00, "Pine"));
    inList.add(new InventoryPlusColor(9, "Ottoman", 3, 110.00, "Black"));
    inList.add(new InventoryPlusColor(10, "Chest of Drawers", 5, 598.00, "White"));
    for (int j = 0; j < inList.size(); j++)
    System.out.println(inList);
    InventoryPlusColor[] inventory = (InventoryPlusColor[]) inList.toArray
    (new InventoryPlusColor[inList.size()]);
    return inventory;
    } // end getInventory() method
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
    private void initComponents() {
    jPanel1 = new javax.swing.JPanel();
    IDNumberLbl = new javax.swing.JLabel();
    IDNumberField = new javax.swing.JTextField();
    prodNameLbl = new javax.swing.JLabel();
    prodNameField = new javax.swing.JTextField();
    colorLbl = new javax.swing.JLabel();
    colorField = new javax.swing.JTextField();
    unitsInStockLbl = new javax.swing.JLabel();
    unitsInStockField = new javax.swing.JTextField();
    unitPriceLbl = new javax.swing.JLabel();
    unitPriceField = new javax.swing.JTextField();
    invenValueLbl = new javax.swing.JLabel();
    invenValueField = new javax.swing.JTextField();
    restockingFeeLbl = new javax.swing.JLabel();
    restockingFeeField = new javax.swing.JTextField();
    jbtFirst = new javax.swing.JButton();
    jbtNext = new javax.swing.JButton();
    jbtPrevious = new javax.swing.JButton();
    jbtLast = new javax.swing.JButton();
    jbtAdd = new javax.swing.JButton();
    jbtDelete = new javax.swing.JButton();
    jbtModify = new javax.swing.JButton();
    jbtSave = new javax.swing.JButton();
    jPanel2 = new javax.swing.JPanel();
    searchIDNumLbl = new javax.swing.JLabel();
    searchIDNumbField = new javax.swing.JTextField();
    jbtSearch = new javax.swing.JButton();
    searchResults = new javax.swing.JLabel();
    jbtExit = new javax.swing.JButton();
    jbtExitwoSave = new javax.swing.JButton();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Inventory Program"));
    IDNumberLbl.setText("ID Number");
    IDNumberField.setEditable(false);
    prodNameLbl.setText("Product Name");
    prodNameField.setEditable(false);
    colorLbl.setText("Product Color");
    colorField.setEditable(false);
    colorField.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    colorFieldActionPerformed(evt);
    unitsInStockLbl.setText("Units In Stock");
    unitsInStockField.setEditable(false);
    unitPriceLbl.setText("Unit Price $");
    unitPriceField.setEditable(false);
    invenValueLbl.setText("Inventory Value $");
    invenValueField.setEditable(false);
    restockingFeeLbl.setText("5% Restocking Fee $");
    restockingFeeField.setEditable(false);
    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
    jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(jPanel1Layout.createSequentialGroup()
    .addContainerGap()
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
    .addComponent(unitPriceLbl)
    .addComponent(unitsInStockLbl)
    .addComponent(colorLbl)
    .addComponent(prodNameLbl)
    .addComponent(IDNumberLbl)
    .addComponent(restockingFeeLbl)
    .addComponent(invenValueLbl))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
    .addComponent(IDNumberField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 176, Short.MAX_VALUE)
    .addComponent(prodNameField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 176, Short.MAX_VALUE)
    .addComponent(colorField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 176, Short.MAX_VALUE)
    .addComponent(unitsInStockField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 176, Short.MAX_VALUE)
    .addComponent(unitPriceField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 176, Short.MAX_VALUE)
    .addComponent(restockingFeeField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 176, Short.MAX_VALUE)
    .addComponent(invenValueField, javax.swing.GroupLayout.DEFAULT_SIZE, 176, Short.MAX_VALUE))
    .addContainerGap())
    jPanel1Layout.setVerticalGroup(
    jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(jPanel1Layout.createSequentialGroup()
    .addContainerGap()
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(IDNumberLbl)
    .addComponent(IDNumberField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(prodNameLbl)
    .addComponent(prodNameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(colorField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(colorLbl))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(unitsInStockField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(unitsInStockLbl))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(unitPriceField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(unitPriceLbl))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(restockingFeeField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(restockingFeeLbl))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 10, Short.MAX_VALUE)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(invenValueField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(invenValueLbl))
    .addContainerGap())
    jbtFirst.setText("First");
    jbtFirst.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jbtFirstActionPerformed(evt);
    jbtNext.setText("Next");
    jbtNext.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jbtNextActionPerformed(evt);
    jbtPrevious.setText("Previous");
    jbtPrevious.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jbtPreviousActionPerformed(evt);
    jbtLast.setText("Last");
    jbtLast.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jbtLastActionPerformed(evt);
    jbtAdd.setText("Add");
    jbtAdd.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jbtAddActionPerformed(evt);
    jbtDelete.setText("Delete");
    jbtModify.setText("Modify");
    jbtModify.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jbtModifyActionPerformed(evt);
    jbtSave.setText("Save");
    jbtSave.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jbtSaveActionPerformed(evt);
    jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Search by:"));
    searchIDNumLbl.setText("Item Number:");
    jbtSearch.setText("Search");
    searchResults.setFont(new java.awt.Font("Tahoma", 1, 12));
    javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
    jPanel2.setLayout(jPanel2Layout);
    jPanel2Layout.setHorizontalGroup(
    jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(jPanel2Layout.createSequentialGroup()
    .addContainerGap()
    .addComponent(searchIDNumLbl)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(jPanel2Layout.createSequentialGroup()
    .addGap(259, 259, 259)
    .addComponent(searchResults, javax.swing.GroupLayout.PREFERRED_SIZE, 213, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
    .addComponent(jbtSearch, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(searchIDNumbField, javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE)))
    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    jPanel2Layout.setVerticalGroup(
    jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(jPanel2Layout.createSequentialGroup()
    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(searchIDNumLbl)
    .addComponent(searchIDNumbField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(jPanel2Layout.createSequentialGroup()
    .addGap(32, 32, 32)
    .addComponent(searchResults, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addGroup(jPanel2Layout.createSequentialGroup()
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jbtSearch)))
    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    jbtExit.setText("Save and Exit");
    jbtExit.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jbtExitActionPerformed(evt);
    jbtExitwoSave.setText("Exit");
    jbtExitwoSave.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jbtExitwoSaveActionPerformed(evt);
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addContainerGap()
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 248, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 44, Short.MAX_VALUE)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
    .addComponent(jbtExitwoSave, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    .addComponent(jbtExit)))
    .addGroup(layout.createSequentialGroup()
    .addComponent(jbtFirst)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jbtNext)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jbtPrevious)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jbtLast))
    .addGroup(layout.createSequentialGroup()
    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    .addGap(12, 12, 12)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
    .addComponent(jbtAdd)
    .addComponent(jbtDelete)
    .addComponent(jbtModify)
    .addComponent(jbtSave))))
    .addContainerGap())
    layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jbtFirst, jbtLast, jbtNext, jbtPrevious});
    layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jbtAdd, jbtDelete, jbtModify, jbtSave});
    layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGap(21, 21, 21)
    .addComponent(jbtAdd)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jbtDelete)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jbtModify)
    .addGap(39, 39, 39)
    .addComponent(jbtSave))
    .addGroup(layout.createSequentialGroup()
    .addContainerGap()
    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(jbtFirst)
    .addComponent(jbtNext)
    .addComponent(jbtPrevious)
    .addComponent(jbtLast))
    .addGap(15, 15, 15)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addGroup(layout.createSequentialGroup()
    .addComponent(jbtExit)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jbtExitwoSave)))
    .addContainerGap())
    pack();
    }// </editor-fold>
    private void jbtExitwoSaveActionPerformed(java.awt.event.ActionEvent evt) {                                             
    System.exit(0);
    private void jbtSaveActionPerformed(java.awt.event.ActionEvent evt) {                                       
    String prodNameMod, colorMod;
    double unitsInStockMod, unitPriceMod;
    int idNumMod;
    idNumMod = Integer.parseInt(IDNumberField.getText());
    prodNameMod = prodNameField.getText();
    unitsInStockMod = Double.parseDouble(unitsInStockField.getText());
    unitPriceMod = Double.parseDouble(unitPriceField.getText());
    colorMod = colorField.getText();
    if(currentProductIndex == inventory.length) {
    inList.add(new InventoryPlusColor(idNumMod, prodNameMod,
    unitsInStockMod, unitPriceMod, colorMod));
    InventoryPlusColor[] inventory = (InventoryPlusColor[]) inList.toArray
    (new InventoryPlusColor[inList.size()]);
    } else {
    inventory[currentProductIndex].setIDNumber(idNumMod);
    inventory[currentProductIndex].setProdName(prodNameMod);
    inventory[currentProductIndex].setUnitsInStock(unitsInStockMod);
    inventory[currentProductIndex].setUnitPrice(unitPriceMod);
    inventory[currentProductIndex].setColor(colorMod);
    displayProduct(inventory[currentProductIndex]);
    private static void writeInventory(InventoryPlusColor i,
    DataOutputStream out) {
    try {
    out.writeInt(i.getIDNumber());
    out.writeUTF(i.getProdName());
    out.writeDouble(i.getUnitsInStock());
    out.writeDouble(i.getUnitPrice());
    out.writeUTF(i.getColor());
    } catch (IOException e) {
    JOptionPane.showMessageDialog(null, "I/O Exception writing data",
    "", JOptionPane.ERROR_MESSAGE);
    System.exit(0);
    } //end writeInventory()
    private static DataOutputStream openOutputStream(String name) {
    DataOutputStream out = null;
    try {
    File file = new File(name);
    out =
    new DataOutputStream(
    new BufferedOutputStream(
    new FileOutputStream(file)));
    } catch (IOException e) {
    JOptionPane.showMessageDialog(null, "I/O Error", "", JOptionPane.ERROR_MESSAGE);
    System.exit(0);
    return out;
    } // end openOutputStream()
    private static void closeFile(DataOutputStream out) {
    try {
    out.close();
    } catch (IOException e) {
    JOptionPane.showMessageDialog(null, "I/O Exception closing file",
    "", JOptionPane.ERROR_MESSAGE);
    System.exit(0);
    } // end closeFile()
    private static DataInputStream getStream(String name) {
    DataInputStream in = null;
    try {
    File file = new File(name);
    in = new DataInputStream(
    new BufferedInputStream(
    new FileInputStream(file)));
    } catch (FileNotFoundException e) {
    JOptionPane.showMessageDialog(null, "The file doesn't exist",
    "", JOptionPane.ERROR_MESSAGE);
    System.exit(0);
    } catch (IOException e) {
    JOptionPane.showMessageDialog(null, "I/O Error creating file",
    "", JOptionPane.ERROR_MESSAGE);
    System.exit(0);
    return in;
    private static void closeInputFile(DataInputStream in) {
    try {
    in.close();
    } catch (IOException e) {
    JOptionPane.showMessageDialog(null, "I/O Exception closing file",
    "", JOptionPane.ERROR_MESSAGE);
    System.exit(0);
    } // end closeInputFile()
    private double entireInventory() {
    // a temporary double variable that the method will return ...
    // after each product's inventory is added to it
    double entireInventory = 0;
    // loop to control number of products
    for (int index = 0; index < inventory.length; index++) {
    // add each inventory to the entire inventory
    entireInventory += inventory[index].setInventoryValue();
    } // end loop to control number of products
    return entireInventory;
    } // end method entireInventory
    private void jbtLastActionPerformed(java.awt.event.ActionEvent evt) {                                       
    currentProductIndex = inventory.length-1; // move to the last product
    // display the information for the last product
    displayProduct(inventory[currentProductIndex]);
    private void jbtPreviousActionPerformed(java.awt.event.ActionEvent evt) {                                           
    if (currentProductIndex != 0) // it's not the first product displayed
    currentProductIndex -- ; // move to the previous product (decrement the current index)
    } else // the first product is displayed
    currentProductIndex = inventory.length-1; // move to the last product
    // after the current product index is set, display the information for that product
    displayProduct(inventory[currentProductIndex]);
    private void jbtNextActionPerformed(java.awt.event.ActionEvent evt) {                                       
    if (currentProductIndex != inventory.length-1) // it's not the last product displayed
    currentProductIndex ++ ; // move to the next product (increment the current index)
    } else // the last product is displayed
    currentProductIndex = 0; // move to the first product
    // after the current product index is set, display the information for that product
    displayProduct(inventory[currentProductIndex]);
    private void jbtFirstActionPerformed(java.awt.event.ActionEvent evt) {                                        
    currentProductIndex = 0;
    // display the information for the first product
    displayProduct(inventory[currentProductIndex]);
    private void colorFieldActionPerformed(java.awt.event.ActionEvent evt) {                                          
    // TODO add your handling code here:
    private void jbtModifyActionPerformed(java.awt.event.ActionEvent evt) {                                         
    prodNameField.setEditable(true);
    prodNameField.setFocusable(true);
    unitsInStockField.setEditable(true);
    unitPriceField.setEditable(true);
    private void jbtAddActionPerformed(java.awt.event.ActionEvent evt) {                                      
    IDNumberField.setText("");
    IDNumberField.setEditable(true);
    prodNameField.setText("");
    prodNameField.setEditable(true);
    colorField.setText("");
    colorField.setEditable(true);
    unitsInStockField.setText("");
    unitsInStockField.setEditable(true);
    unitPriceField.setText("");
    unitPriceField.setEditable(true);
    restockingFeeField.setText("");
    invenValueField.setText("");
    currentProductIndex = inventory.length;
    private void jbtExitActionPerformed(java.awt.event.ActionEvent evt) {                                       
    DataOutputStream out = openOutputStream("inventory.dat");
    for (InventoryPlusColor i : inventory)
    writeInventory(i, out);
    closeFile(out);
    System.exit(0);
    private static InventoryPlusColor readProduct(DataInputStream in) {
    int idNum = 0;
    String prodName = "";
    double inStock = 0.0;
    double pric

    BalusC -- The line that gives me my NullPointerException is when I call the "DisplayProduct()" method. Its a dumb question, but with NetBeans how do I find out which reference could be null? I'm not very familiar with how NetBeans works with finding out how to debug. Any help you can give me would be greatly appreciated.The IDE is com-plete-ly irrelevant. It's all about the source code.
    Do you understand anyway when and why a NullPointerException is been thrown? It is a subclass of RuntimeException and those kind of exceptions are very trival and generally indicate an design/logic/thinking fault in your code.
    SomeObject someObject = null; // The someObject reference is null.
    someObject.doSomething(); // Invoking a reference which is null would throw NPE.

  • A problem with ArrayLists

    Hello
    I'm pretty new to Java, and sometimes all those objects, instances, classes, data types etc confuse me. I'm having some kind of a problem with ArrayLists (tried with vectors too, didn't work) . I'm writing a program which takes float numbers from user input and does stuff to them. No syntax error in my code, but I get a java.lang.ClassCastException when I run it.
    I insert stuff to the ArrayList like this:
    luku.add(new Float(syotettyLuku));no problem
    I'm trying to access information from the list like this inside a while loop
    float lukui = new Float((String)luku.get(i)) .floatValue();but the exception comes when the programme hits that line, no matter which value i has.
    Tried this too, said that types are incompatible:
    float lukui = ((float)luku.get(i)) .floatValue();What am I doing wrong? I couldn't find any good tutorials about using lists, so i'm really lost here.
    I'll post the whole code here, if it helps. Sorry about the Finnish variable and method names, but you get the idea :)
    package esa;
    import java.io.*;
    import java.util.*;
    public class Esa {
    static final int maxLukuja = 100;
    static BufferedReader syote = new BufferedReader(new InputStreamReader(System.in));
    static String rivi;
    static String lopetuskasky = "exit";
    static double keskiarvo;
    static ArrayList luku = new ArrayList();
    static int lukuja;
    static float summa = 0;
    // M��ritell��n pari metodia, joiden avulla voidaan tarkastaa onko tarkasteltava muuttuja liukuluku
    static Float formatFloat(String rivi) {
        if (rivi == null) {
            return null;
        try {
            return new Float(rivi);
        catch(NumberFormatException e) {
            return null;
    static boolean isFloat(String rivi) {
        return (formatFloat(rivi) != null);
    // Luetaan luvut k�ytt�j�lt� ja tallnnetaan ne luku-taulukkoon
    static void lueLuvut() throws IOException{
        int i = 0;
        float syotettyLuku;
        while(i < maxLukuja) {
            System.out.println("Anna luku kerrallaan ja paina enter. Kun halaut lopettaa, n�pp�ile exit");
            rivi = syote.readLine();
            boolean onkoLiukuluku = isFloat(rivi);
            if (onkoLiukuluku) {
                syotettyLuku = Float.parseFloat(rivi);
                if (syotettyLuku == 0) {
                    lukuja = luku.size();              
                    break;
                }  // if syotettyluku
                else {
                    luku.add(new Float(syotettyLuku));
                    i++;
                } // else
            } // if onkoLiukuluku
            else {
               System.out.println("Antamasi luku ei ole oikeaa muotoa, yrit� uudelleen.");
               System.out.println("");
            } // else
        } // while i < maxlukuja
    // lueLuvut
    static void laskeKeskiarvo() {
        int i = 0;
        while(i < lukuja) {
            float lukui = ((float)luku.get(i)) .floatValue();
            System.out.println(lukui);
            summa = summa + lukui;
        }   i++;
        keskiarvo = (summa / lukuja);
    } // laskeKeskiarvo
    public static void main(String args[]) throws IOException {
    lueLuvut();
    laskeKeskiarvo();
    } // main
    } // class

    Thanks! Now it's functioning.
    As I mentioned, I tried this:
    float lukui = ((float)luku.get(i))
    .floatValue();And your reply was:
    float lukui =
    ((Float)luku.get(i)).floatValue So the problem really was the spelling, it should
    have been Float with a capital F.
    From what I understand, Float refers to the Float
    class, Correct. And float refers to the float primitive type. Objects and primitives are not interchangeable. You need to take explicit steps to convert between them. Although, in 1.5/5.0, autoboxing/unboxing hide some of this for you.
    so why isn't just a regular float datatype
    doing the job here, like with the variable lukui?Not entirely sure what you're asking.
    Collections take objects, not primitives, and since you put an object in, you get an object out. You then have to take the extra step to get a primitive representation of that object. You can't just cast between objects and primitives.
    Again, autoboxing will relieve some of this drudgery. I haven't used it myself yet, so I can't comment on how good or bad it is.

Maybe you are looking for

  • CPU not showing up in System Profiler

    Hi, I have a 4 year old Dual 2.5 GHz G5 which I think has had a CPU failure (B CPU). The system profiler states that I only have one, not two CPU's. Is it a case of using a repair CD to reset the lost CPU or is it dead? Any ideas anyone? Thanks in ad

  • My Setting, Contacts and reminders has stopped working.  I am on IOS5

    Settings, reminders, contacts have stopped working.  settings opens but locks up.  Reminders and contacts open but there is nothing there.

  • I can't select text within a text frame.

    I'm very rusty with InDesign, so forgive me if this is a stupid question. I am simply trying to select text to cut and paste it. I have the Text tool selected, but I can't seem to select the text that's already in the text frame. The cursor doesn't e

  • Event handling across master/detail regions.

    Hi, I have a table displaying a few targets in the master region and the details of the selected target are shown in an other region. The selected target is passed as an input parameter to the dependent region. Both these regions are displayed in one

  • PL/SQL Escape Characters?

    I've built a procedure that displays a list using htp's. The procedure contains a call to this function: FUNCTION "GET_JOBNAME"(p_jobid in varchar2) RETURN VARCHAR2 AS p_jname varchar2(100); BEGIN select job_title into p_jname from jobs where job_id