About ArrayList....

Hi
Hope you are fine.
I have been stuck in a problem, can u plz help?
Hoping for a quick response, thanks alot.
Kind Regards,
fastian
code is here along with comments and problem descriptions.
public boolean getProductList(ArrayList prodList)
/* Caller has declared it as
ArrayList tempList=new ArrayList();
Assume we have 3 rows in DB as follows:
ID     name     category     purchasePrice     salePrice     quantity     threshold     expiry
1     milk     category 1     20     25     100     10     1/1/2007
2     cream     cat2     0     0     0     0 10     1/1/2007
3     sugar     cat3     0     0     0     0 10     1/1/2007
Also Assume that the "Product" class has declared as follows:
public String id;
public String name;
public String catagory;
public int purchasePrice;
public int salePrice;
public int quantity;
public int threshold;
String sql = "SELECT * FROM product";
        cm = new connectionMngr();
        Product prod=new Product();
        Product prod1=new Product();
        System.out.println(sql);
        try
            rs = cm.executeQuery(sql);
            int i=0;
            while(rs.next())
                prod.id= rs.getString("id");
                prod.name= rs.getString("name");
                prod.catagory= rs.getString("category");
                prod.purchasePrice= rs.getInt("purchasePrice");
                prod.salePrice= rs.getInt("salePrice");
                prod.quantity= rs.getInt("quantity");
                prod.threshold= rs.getInt("threshold");
                if(prodList.add((Object)prod))
                    //System.out.println(prod.id + " in DL");
                }/*Till this line the prodList contains valid rows*/
System.out.println(((Product)prodList.get(i)).id+"--Varify");/*The line above, prints 1, 2 , and
3 in three iterations*/
  i++;
            System.out.println("Prod successsfully added!!!!");
            cm.close();/*But here comes the source of problem, that is, all three lines print "3"
which is assumed to be the output of 3rd line ONLY*/
                System.out.println(((Product)prodList.get(0)).id+"--Varify22");
                System.out.println(((Product)prodList.get(1)).id+"--Varify22");
                System.out.println(((Product)prodList.get(2)).id+"--Varify22");
            return true;
        catch(Exception e)
            e.printStackTrace();
            System.out.println("Exception has been caught!!!!");
            cm.close();
             return false;
    }

Hi Dear,
Please user the following code to solve your problem
String sql = "SELECT * FROM product";
cm = new connectionMngr();
// Product prod=new Product(); //.........(1)
Product prod1=new Product();
System.out.println(sql);
try
rs = cm.executeQuery(sql);
int i=0;
while(rs.next())
Product prod=new Product(); // ................(2)
prod.id= rs.getString("id");
prod.name= rs.getString("name");
prod.catagory= rs.getString("category");
prod.purchasePrice= rs.getInt("purchasePrice");
prod.salePrice= rs.getInt("salePrice");
prod.quantity= rs.getInt("quantity");
prod.threshold= rs.getInt("threshold");
if(prodList.add((Object)prod))
//System.out.println(prod.id + " in DL");
I have corrected the code as above .Please check at line mark as (1) and (2)
thanks
sushil

Similar Messages

  • Help about ArrayList on method

    Hi all , i have a prole about receving an ArrayList on a method.
    here is the code:
    //here is where i make the ArrayList
    private static java.util.ArrayList subStrs(String line, int tipo)
         java.util.ArrayList psline = new java.util.ArrayList();
                        psline.add(line.substring(0, 7));
                        psline.add(line.substring(7, 17));
                        psline.add(line.substring(17, 23));
                        psline.add(line.substring(23, 28));
         return psline;
    //here i pass the parameter
    private static void insereLinha(java.util.ArrayList psline, int tipo, int id) throws Exception {
                        if (psline.get(3).toString().toUpperCase().equals("FECHA"))
                             Y= ", 1)";
                        else
                             Y= ", 0)";
                        sql= "insert into HPA values (?, " + psline.get(0) + ", " + arruma.hourToSeconds(psline.get(2).toString()) + Y;
                        pst= con.prepareStatement(sql);
                        pst.setDate(1, new java.sql.Date(sdf.parse(psline.get(1).toString()).getTime()));
                        break;
    i call it from here :
    public static void main(String[] args) throws Exception {
              while (rs.next()) {
                   try {
                        linhas = rs.getString("ds_erros");
                        cds = rs.getInt("cd_erros");
                        ids = rs.getInt("id_erros");
                        //here is the problem
    insereLinha(subStrs(linhas, cds), cds, ids);
                        deletaLinha(rs.getInt("id_erros"));
                   } catch (SQLException e) {
                        throw e;
    i get the Exception :
    "Unable to print result (toString failed)
    tks all
    Sandro

    Hi,
    Your code looks like it should work. I have used part of your code and the following code works. Compare it to what you are doing ...
    import java.util.*;
    public class Array2Test
      private static ArrayList subStrs( String line, int tipo )
        ArrayList psline = new ArrayList();
        psline.add( line.substring( 0, 7 ) );
        psline.add( line.substring( 7, 17 ) );
        psline.add( line.substring( 17, 23 ) );
        psline.add( line.substring( 23, 28 ) );
        return( psline );
      private static void insereLinha( ArrayList psline, int tipo, int id)
        throws Exception
        for( int i = 0; i < psline.size(); ++i )
          System.out.println( psline.get( i ) );
      public static void main(String[] args) throws Exception
        String linhas = "0123456789012345678901234567";
        int cds = 24;
        int ids = 12;
        //here is the problem
        insereLinha( subStrs(linhas, cds), cds, ids );
    }Regards,
    Manfred.

  • ArrayLists

    I don't understand something about arrayLists. The add method and set method return a value (true and an object). But you can just use the add and set command without having that return value.
    ArrayList list = new ArrayList()
    list.add(new Integer(0));
    list.add(1, new Integer(1)):
    // I don't have to put:
    boolean value = list.add(newInteger(0));
    // Why is this so?

    your misunderstanding applies to all cases where you might use a method and ignore the return value.
    Why is this so?A return instruction places the result on the invokers frame operand stack. If the compiler detects the return value is not being used, it generates a pop command to dispose of the unused value. The one exception to the above is that a void method results in a special return instruction which does not place anything on the invokers stack.
    In other words, just be glad it is so.

  • Need help in putting data into 2d array

    My input file :
    1 , 2 , 1
    2 , 2 , 1
    3 , 3 , 1
    4 , 2 , 2
    2 , 3 , 2I'm stuck at:
    while( reader.readLine() != null){
    String Matrix[] = line.split(",");
    }Means I only can read how many lines there. For 2d array, Matrix[i][j], is that when I count the line, the number of count will be the 'i'? How about 'j'? Am I need to count i and j before put the data into 2d array?
    Do correct me if something wrong in:
    while( reader.readLine() != null){
    String Matrix[] = line.split(",");
    } Thank you.

    gtt0402 wrote:
    while( reader.readLine() != null){
    String Matrix[] = line.split(",");
    How about:
    ArrayList<String[]> rows = new ArrayList<String[]>();
    while((line = reader.readLine()) != null) {
        rows.add(line.split(","));
    }After the loop you have a list full of String arrays and you can convert it to a 2D String array if you wish.

  • At end of tether!  Reading in variables from a text file

    Hi all
    My stress factor has gone through the roof because I am trying to read in from a text file (you may have seen some earlir questions about ArrayLists) it's just not working!
    The code is below. The result is that it's reading in all of the car data, none of the motorbike and only the first line for the services. It's odd and it's driving me insane!
    Here's an example of the data it's reading. There are about 7-10 sets of data per type
    <car><reg>AB04CDE</reg><make>Ford</make><model>Fiesta</model><colour>blue</colour><passenger_no>4</passenger_no></car>
    <service><service_no>13570</service_no><reg>J605PLE</reg><date>15:07:2006</date><miles>20000</miles><part_replaced>brake_pads</part_replaced><part_replaced>front_tyres</part_replaced></service>
    <motorbike><reg>TT05EKJ</reg><make>Triumph</make><model>Speedmaster</model><colour>black</colour><load>20.50</load></motorbike>
    Here's the code
    while (moreToRead) {
            String line;
            try {
              line = fileReader.getNextStructure();
    // collect the data from the file
              if (line.indexOf("<car>")> -1){
                // Select/Extract the registration element
                int nStart = line.indexOf("<reg>");
                int nEnd = line.indexOf("</reg>");
                String reg = line.substring(nStart+5,nEnd);
                // Select/Extract the make element
                nStart = line.indexOf("<make>");
                nEnd = line.indexOf("</make>");
                String make = line.substring(nStart+6,nEnd);
                // Select/Extract the model element
                nStart = line.indexOf("<model>");
                nEnd = line.indexOf("</model>");
                String model = line.substring(nStart+7,nEnd);
                // Select/Extract the colour element
                nStart = line.indexOf("<colour>");
                nEnd = line.indexOf("</colour>");
                String colour = line.substring(nStart+8,nEnd);
                // Select/Extract the passenger_no element
                nStart = line.indexOf("<passenger_no>");
                nEnd = line.indexOf("</passenger_no>");
                String passenger_no = line.substring(nStart+14,nEnd);
                //convert string to int
                int passengerInt = Integer.parseInt(passenger_no);
                // declare new object car and assign the variables then add it to the array.
                Car c = new Car (reg, make, model, colour, passengerInt);
                carList.add(c);
      } else if (line.indexOf("<bike>")> -1) {
             // Select/Extract the registration element
             int nStart = line.indexOf("<reg>");
             int nEnd = line.indexOf("</reg>");
             String reg = line.substring(nStart+5,nEnd);
             // Select/Extract the make element
             nStart = line.indexOf("<make>");
             nEnd = line.indexOf("</make>");
             String make = line.substring(nStart+6,nEnd);
             // Select/Extract the model element
             nStart = line.indexOf("<model>");
             nEnd = line.indexOf("</model>");
             String model = line.substring(nStart+7,nEnd);
             // Select/Extract the colour element
             nStart = line.indexOf("<colour>");
             nEnd = line.indexOf("</colour>");
             String colour = line.substring(nStart+8,nEnd);
             // Select/Extract the load element
             nStart = line.indexOf("<load>");
             nEnd = line.indexOf("</load>");
             String load = line.substring(nStart+6,nEnd);
             //convert load string to double
             double bikeLoad = Double.parseDouble(load);
             // declare new object motorbike and assign the variables then add it to the array.
             Motorbike m = new Motorbike (reg, make, model, colour, bikeLoad);
             bikeList.add(m);
      } else  {
        // Select/Extract the service_number element
        int nStart = line.indexOf("<service_no>");
        int nEnd = line.indexOf("</service_no>");
        String service_no = line.substring(nStart+12,nEnd);
        console.println("service = " + service_no);
        nStart = line.indexOf("<reg>");
        nEnd = line.indexOf("</reg>");
        String reg = line.substring(nStart+5,nEnd);
        console.println("service = " + reg);
        nStart = line.indexOf("<date>");
        nEnd = line.indexOf("</date>");
        String date = line.substring(nStart+6,nEnd);
        console.println("service = " + date);
        nStart = line.indexOf("<miles>");
        nEnd = line.indexOf("</miles>");
        String miles = line.substring(nStart+7,nEnd);
        console.println("service = " + miles);
        nStart = line.indexOf("<part_replaced>");
        nEnd = line.indexOf("</part_replaced>");
        String part_replaced = line.substring(nStart+15,nEnd);
        console.println("service = " + part_replaced);
        //convert string to int
        int dateOfService = Integer.parseInt(date);
        //convert string to double
        double milesAtService = Double.parseDouble(miles);
        //convert service no to unique int
        int serviceNo = Integer.parseInt(service_no);
        // declare new object service and assign the variables then add it to the array.
        Service s = new Service (reg, part_replaced, serviceNo, dateOfService, milesAtService);
          serviceList.add(s);
          catch (Exception e) {
            // Run out of data
            moreToRead = false;
    } If anyone can spy anything that could be causing this I love your advice. I simply can't see it.
    Jo

    hi jos,
    we have been asked not to use a parser for this assignment. evil
    tutor i think! lolYour example seems to imply that all the <tag> ... </tag> pairs have
    to occur on a single line; if that is so, you can do some cheap
    programming like this:String getText(String line, String tag) {
       int start= line.indexOf("<"+tag+">");
       int end= line.indexOf("</"+tag+">", start);
       if (start < 0 || end < 0) return null; // no <tag> ... </tag> pair found
       // return the text in between the <tag> ... </tag> tags
       return line.substring(start+tag.length()+2, end);
    }kind regards,
    Jos

  • Help on array

    Hi, I want to sort an array which contains Strings (sort according to alphabetical order...)
    after i sort the array...i want to read it at it's original order too...
    that mean's i want to have 2 set of array.....1 with the original order...1 with the sorted order..
    how do i do that?
    let's say i have a container class Club with an array of Names(type String), and a client class...
    with a Club object memberList.how do i do that?
    thank you.

    that mean's i want to have 2 set of array.....1 with
    the original order...1 with the sorted order..OK, how about
      ArrayList origArray = ... whatever ...;
      ArrayList sorted = new ArrayList(origArray);
      Collections.sort(sorted);Now, origArray still has your data in the original order, sorted has it in the sorted order. Note: both are pointing to the same elements.

  • Using objects rather than jdbc resultset to fill reports

    Hi buddies!
    I�m developing a small sample of application that generates reports using values retrieved from objects.
    The idea is simple, I have an arraylist of objects and want to fill my report which these objects atributes.
    Jasper Project API has a class called JasperFillManager which is used to fill reports and takes 3 arguments, for instance:
    JasperFillManager.fillReport(JasperReport reporttofill,HashMap parameters, JRDataSource dataSource)
    I�ve created a custom JRDataSource named fonteDadosJasperCustomizada
    This class implements an arraylist of objects and two methods from the interface JRDataSource which are responsible for giving the values to fill the report. This class doesn�t take values from a resultset! ;)
    but for some reason nothing appears to me after executing the application... everything is alright I think the might be a mistake in the interface methods, the report also is alright.
    All sugestions are welcome
    thanks
    import java.sql.*;
    import java.util.HashMap;
    import java.util.Map;
    import net.sf.jasperreports.engine.JasperCompileManager;
    import net.sf.jasperreports.engine.JasperFillManager;
    import net.sf.jasperreports.engine.JasperPrint;
    import net.sf.jasperreports.engine.JasperReport;
    import net.sf.jasperreports.engine.design.JasperDesign;
    import net.sf.jasperreports.engine.xml.JRXmlLoader;
    import net.sf.jasperreports.view.JasperViewer;
    public class relatorioteste1{
         public relatorioteste1(){
         try{     
              fonteDadosJasperCustomizada fonte = new fonteDadosJasperCustomizada();
              JasperDesign relatoriocarregado = JRXmlLoader.load("c:/relatorioteste1.jrxml");          
              JasperReport relatoriocompilado = JasperCompileManager.compileReport(relatoriocarregado);
              /*the parameter fonte being passed to fillManager is a custom JRDataSource.
              * The default JRResultSetDataSource only receives a JDBC ResultSet and
              * extracts Data from it to fill the Report, such Object is implements
              * the JRDataSource interface which defines methods that are used by
              * fillManager to obtain data from the ResultSet.
              * My intention is to create my own JRDataSource class which should
              * be able to retrieve data from objects instead of ResultSet
              * See class fonteDadosJasperCustomizada for details
              JasperPrint relatorioimpresso = JasperFillManager.fillReport(relatoriocompilado,new HashMap(),fonte);
              JasperViewer.viewReport(relatorioimpresso);
         catch(Exception e){
              javax.swing.JOptionPane.showMessageDialog(null, e.getMessage());
         public static void main(String args[]){
              new relatorioteste1();
    import net.sf.jasperreports.engine.JRDataSource;
    import net.sf.jasperreports.engine.JRException;
    import net.sf.jasperreports.engine.JRField;
    import java.util.ArrayList;
    public class fonteDadosJasperCustomizada implements JRDataSource {
         public Object getFieldValue(JRField arg0) throws JRException{
         /*The following line returns the next object(aluno) from
         * the arraylist collection
              Aluno aluno = (Aluno) dados.listIterator().next();
         /*This block verifies which column value(field) is being
         * requested by the jasperFillManager.fillReport and returns
         * an object value corresponding to the field
              if ("codigo".equals(arg0.getName()))
                   return Integer.valueOf(aluno.getCodigo());
              else if ("nome".equals(arg0.getName()))
                   return aluno.getNome();
              else
                   return Integer.valueOf(aluno.getIdade());     
              public boolean next() throws JRException{
              /*this decision verifies if there�re more elements in
              * the arraylist collection if so returns true... else returns
              * false
              if (dados.listIterator().hasNext())
                   return true;
              else
                   return false;
         public fonteDadosJasperCustomizada(){
              /*The constructor of my custom JRResulSetDataSource should receive
              * a JDBC ResultSet in place of an Arraylist of Objects
              * The atributes of each object is mapped to a field in
              * jasperreports template
              dados = new ArrayList();
              dados.add(new Aluno(1,"charlles cuba",25));
              dados.add(new Aluno(2,"Maicom napolle",25));
              dados.add(new Aluno(3,"Gustavo castro",21));          
         public static void main(String args[]){
              new fonteDadosJasperCustomizada();
         ArrayList dados;     
    }

    Buddies thansk everyone
    I�m really grateful... the previous post in here was very useful to me. I
    was wrong about ArrayList.listIterator.
    I finnaly generated a report from an arraylist of objects.
    Here�s the code... I made some changes the first one was wrong
    HERE IS MY MAIN CLASS RESPONSIBLE FOR GENERATING THE REPORT
    public class relatorioteste1{     
         public relatorioteste1(){
              try{     
                   fonteDadosJasperCustomizada fonte = new fonteDadosJasperCustomizada();
                   JasperDesign relatoriocarregado = JRXmlLoader.load("c:/relatorioteste1.jrxml");          
                   JasperReport relatoriocompilado = JasperCompileManager.compileReport(relatoriocarregado);                    
                   JasperPrint relatorioimpresso = JasperFillManager.fillReport(relatoriocompilado,new HashMap(),fonte);
                   JasperViewer.viewReport(relatorioimpresso);
              catch(Exception e){
                   javax.swing.JOptionPane.showMessageDialog(null, e.getMessage());
         public static void main(String args[]){
              new relatorioteste1();
    HERE IS MY CUSTOM JRDATASOURCE
    public class fonteDadosJasperCustomizada implements JRDataSource {
         public Object getFieldValue(JRField arg0) throws JRException{     
              if ("codigo".equals(arg0.getName()))
                   return Integer.valueOf(aluno.getCodigo());
              else if ("nome".equals(arg0.getName()))
                   return aluno.getNome();
              else
                   return Integer.valueOf(aluno.getIdade());
         public boolean next() throws JRException{
              if (iterator.hasNext()){
                   aluno = (Aluno) iterator.next();                    
                   return true;
              else
                   return false;          
         public fonteDadosJasperCustomizada(){          
              dados = new ArrayList();
              dados.add(new Aluno(1,"charlles cuba",25));
              dados.add(new Aluno(2,"Maicom napolle",25));
              dados.add(new Aluno(3,"Gustavo castro",21));
              iterator = dados.listIterator();
         public static void main(String args[]){
              new fonteDadosJasperCustomizada();
         ArrayList dados;
         Iterator iterator;
         Aluno aluno;
    }

  • How to create a final object

    Hello
    I create an ArrayList with some set of values.
    Now i dont want the ArrayList to be modified.
    How is this possible?

    You are not allowed to modify the API classes.
    So you may create a new class and use ArrayList instance in the class. So, you can provide a method for your operation about ArrayList class.
    Regards,
    Mert

  • How do you print items from an array list that fit a certain condition?

    I have an array list full of people. People can be set to single or married, is there anyway I can just display the people from the arraylist that are married? I've been reading through alot of stuff about arraylists and there doesnt seem to be anything on printing things depending on context.

    thebigfish wrote:
    I have an array list full of people. People can be set to single or married, is there anyway I can just display the people from the arraylist that are married? I've been reading through alot of stuff about arraylists and there doesnt seem to be anything on printing things depending on context.Have you tried simply iterating over the list, checking for your condition, and printing out the person's details?
    for ( Person p : yourListOfPeople ) {
        if ( p.isMarried() ) {    // Assuming isMarried returns a boolean value determining if the person is married
            System.out.println( p );  // Assuming you've overriden toString
    }

  • Dynamically naming objects

    I'm looking for a way to name my objects, without having to name them in hard-code, so instead of
    Item randomName = new Item();I could do something like
    for(int i=0;i<10;i++){
    Item i = new Item();
    }Which would hopefully give me 10 new items, named 1-10. I'm sure this must be possible, but I imagine I am approaching it completely wrong. And help would be appreciated.

    cheesysam wrote:
    Okay. I'll forget trying to give them names. And read up about ArrayLists. Thanks for the help. Like I said I think I'm just approaching it wrong.A List (like ArrayList or LinkedList) is what you'd use if you don't carea about duplicates, but do care about the ordering of the things, but you only want to access them sequentially or by index.
    A Set (like HashSet) is what you'd use if you don't care about order, don't want duplicates, and are going to process them sequentially (as opposed to picking one out by "name").
    If you want no dupes AND care about order, use a LinkedHashSet (to preserve insertion order) or a SortedSet (like TreeSet) to keep them sorted by some attribute(s).
    If you want to retrieve things randomly by "name" or some other non-numeric property, use a Map (like HashMap).

  • Confused about objects in ArrayLists

    Alright, this is what I am trying to do:
    1.I collect the first name, last name, number, points, rebounds, assists, and fouls all in the stats object.
    Here is my main code:
        public static void main(String[] args) {
            String input;
            String input1;
            String firstName;
            String lastName;
            int gameNumber = 0;
            int points = 0;
            int rebounds = 0;
            int fouls = 0;
            int assists = 0;
            int i = 0;
            ArrayList<Stats> player = new ArrayList<Stats>();
            do{
                Stats stats = new Stats();
                Scanner keyboard = new Scanner(System.in);
                System.out.println("Do you want to enter data or quit(E-enter, Q-quit)?");
                input1 = keyboard.nextLine();
                if (input1.equalsIgnoreCase("E")){
                    System.out.println("What is player's first name? ");
                    firstName = keyboard.nextLine();
                    stats.setFirstName(firstName);
                    System.out.println("What is player's last name? ");
                    lastName = keyboard.nextLine();
                    stats.setLastName(lastName);
                    System.out.println("What is player's game number? ");
                    gameNumber = keyboard.nextInt();
                    stats.setGameNumber(gameNumber);
                    System.out.println("How many points were scored? ");
                    points = keyboard.nextInt();
                    stats.setPoints(points);
                    System.out.println("How many rebounds? ");
                    rebounds = keyboard.nextInt();
                    stats.setRebounds(rebounds);
                    System.out.println("How many fouls? ");
                    fouls = keyboard.nextInt();
                    stats.setFouls(fouls);
                    System.out.println("How many assists? ");
                    assists = keyboard.nextInt();
                    stats.setAssists(assists);
                    player.add(stats);
                System.out.println(stats);
                System.out.println("Do you want to get a players info or average, enter or quit (I-Info, A-average,E-entry,Q-quit)?");
                input = keyboard.nextLine();
                System.out.println(input);
            } while (!input.equalsIgnoreCase("Q"));
    }I also have a Stats.java code that gets/sets each points rebounds...etc.
    And thats all fine.... but now I want to put stats in an ArrayList, and be able to access each added stats by the user typing a last name.
    AKA:
    Input: Thompson
    Output: points, rebounds, assists, fouls
    So am I on the right road by just adding stats into player every loop, and how do I access it with just a last name?
    If u do not understand just ask and Ill explain better.
    Thanks guys

    Ight thanks, I got that to work but now I have another question....
    Here is my code:
      public static void main(String[] args) {
            String input;
            String input1;
            String firstName;
            String lastName;
            int gameNumber = 0;
            int points = 0;
            int rebounds = 0;
            int fouls = 0;
            int assists = 0;
            ArrayList s1 = new ArrayList<Stats>();
            do{
                Stats stats = new Stats();
                Scanner keyboard = new Scanner(System.in);
                System.out.println("Do you want to enter data or quit(E-enter, Q-quit)?");
                input1 = keyboard.nextLine();
                if (input1.equalsIgnoreCase("E")){
                System.out.println("What is player's first name? ");
                firstName = keyboard.nextLine();
                stats.setFirstName(firstName);
                s1.add(firstName);
                System.out.println("What is player's last name? ");
                lastName = keyboard.nextLine();
                stats.setLastName(lastName);
                s1.add(lastName);
                System.out.println("What is player's game number? ");
                gameNumber = keyboard.nextInt();
                stats.setGameNumber(gameNumber);
                s1.add(gameNumber);
                System.out.println("How many points were scored? ");
                points = keyboard.nextInt();
                stats.setPoints(points);
                s1.add(points);
                System.out.println("How many rebounds? ");
                rebounds = keyboard.nextInt();
                stats.setRebounds(rebounds);
                s1.add(rebounds);
                System.out.println("How many fouls? ");
                fouls = keyboard.nextInt();
                stats.setFouls(fouls);
                s1.add(fouls);
                System.out.println("How many assists? ");
                assists = keyboard.nextInt();
                stats.setAssists(assists);
                s1.add(assists);
                System.out.println("Do you want to get a players info or average, enter or quit (I-Info, A-average,E-entry,Q-quit)?");
                input = keyboard.nextLine();
                System.out.println(input);
                /*if (input.equalsIgnoreCase("I")){
                    System.out.println("Enter player's last name: ");
                    String lastNameInfo = keyboard.nextLine();
                    for (int i=1; i<s1.size(); i=i+7){
                        if (lastNameInfo.equalsIgnoreCase((String)s1.get(i))) {
                            System.out.println((String)s1.get(i-1) + (String)s1.get(i) + " had " +
                                    (String)s1.get(i+2) + " points, " + (String)s1.get(i+3) +
                                    " rebound, " + (String)s1.get(i+4) + "fouls, and " +
                                    (String)s1.get(i+5) + "assists.");
                        } else;
                        System.out.println("That player is not on the roster.");
            } while (input.equalsIgnoreCase("E"));
    }And here is my output:
    init:
    deps-jar:
    compile:
    run:
    Do you want to enter data or quit(E-enter, Q-quit)?
    e
    What is player's first name?
    Jon
    What is player's last name?
    Doe
    What is player's game number?
    1
    How many points were scored?
    1
    How many rebounds?
    1
    How many fouls?
    1
    How many assists?
    1
    Do you want to get a players info or average, enter or quit (I-Info, A-average,E-entry,Q-quit)?
    BUILD SUCCESSFUL (total time: 13 seconds)Why does it not let the user put an answer in for the last question ("Do you want to get a players info or average, enter or quit (I-Info, A-average,E-entry,Q-quit)?")
    Thanks

  • How to input data into an arraylist from a text file?

    I am trying to take data from a text file and put that data into an arraylist. First here is the text file:
    [item1, 10, 125.0, item2, 10, 12.0, item3, 20, 158.0]
    3
    4530.0
    [item5, 65, 555.5, item4, 29, 689.0]
    2
    56088.5
    [item7, 84, 34.5, item6, 103, 0.5, item8, 85, 1.36]
    3
    3065.1The text between the [ ] is the output from my arraylists. I have three arraylists. The first [ ] belongs to arraylist A, the second to arraylist B, and the third to arraylist C. The format of the arraylists is this:
    <item name>,<# in stock>,<value of one item>
    The first number below the arraylists in the text file represents the number of items in the list. The second number below the arraylists represents the total value of the items in the arraylists.
    Here is the class file I have (yes, it does everything):
    import java.io.*;
    import java.util.Scanner;
    import java.util.ArrayList;
    public class Inventory extends Object
         public int toAdd = 0;
         private boolean done = false;               //Are we done yet?
         public String strItemName;                    //The name of the item type.
         public int intNumInStock;                    //The number in stock of that type.      
         public double dblValueOfOneItem;          //The value of one item.
        public String strNumberInStock;               
        public double dblTotalValueA;               //The total value of warehouse A.
        public double dblTotalValueB;               //The total value of warehouse B.
        public double dblTotalValueC;               //The total value of warehouse C.
        public int intWarehouseAItemCount;          //Counter for items in warehouse A.
        public int intWarehouseBItemCount;          //Counter for items in warehouse B.
        public int intWarehouseCItemCount;          //Counter for items in warehouse C.
         ArrayList warehouseAList = new ArrayList();     //Create the Warehouse A ArrayList.                                   
         ArrayList warehouseBList = new ArrayList(); //Create the Warehouse B arrayList.
         ArrayList warehouseCList = new ArrayList(); //Create the Warehouse C arrayList.
         /** Construct a new Inventory object. */
         public Inventory()
              super();
         /**Add items to the Warehouse A ArrayList.*/
         private void createWareHouseA()
              System.out.println("!" + toAdd + " item types will be added to warehouse A.");
              //Cast
              String strNumInStock = Integer.toString(intNumInStock);
              String strValueOfOneItem = Double.toString(dblValueOfOneItem);
              this.strNumberInStock = strNumInStock;
              System.out.println("!Initial size of warehouseAList :  " +
                                                                warehouseAList.size());
              //Add items to the array List
              warehouseAList.add(this.strItemName);
              warehouseAList.add(this.strNumberInStock);
              warehouseAList.add(this.dblValueOfOneItem);
              System.out.println("!size of arrayList after additions " + warehouseAList.size());
         /**Add items to the Warehouse B ArrayList.*/
         private void createWareHouseB()
              System.out.println("!" + toAdd + " item types will be added to warehouse B.");
              //Cast
              String strNumInStock = Integer.toString(intNumInStock);
              String strValueOfOneItem = Double.toString(dblValueOfOneItem);
              this.strNumberInStock = strNumInStock;
              System.out.println("!Initial size of warehouseBList :  " +
                                                                warehouseBList.size());
              //Add items to the array List
              warehouseBList.add(this.strItemName);
              warehouseBList.add(this.strNumberInStock);
              warehouseBList.add(this.dblValueOfOneItem);
              System.out.println("!size of arrayList after additions " + warehouseBList.size());
         /**Add items to the Warehouse C ArrayList.*/
         private void createWareHouseC()
              System.out.println("!" + toAdd + " item types will be added to warehouse C.");
              //Cast
              String strNumInStock = Integer.toString(intNumInStock);
              String strValueOfOneItem = Double.toString(dblValueOfOneItem);
              this.strNumberInStock = strNumInStock;
              System.out.println("!Initial size of warehouseCList :  " +
                                                                warehouseCList.size());
              //Add items to the array List
              warehouseCList.add(this.strItemName);
              warehouseCList.add(this.strNumberInStock);
              warehouseCList.add(this.dblValueOfOneItem);
              System.out.println("!size of arrayList after additions " + warehouseCList.size());
         /**Interpret the commands entered by the user.*/
         public void cmdInterpreter()
              this.displayHelp();
              Scanner cin = new Scanner(System.in);
              while (!this.done)
                   System.out.print(">");
                   //"line" equals the next line of input.
                   String line = cin.nextLine();
                   this.executeCmd(line);
         /**Execute one line entered by the user.
          * @param cmdLN; The command entered by the user to execute. */
          private void executeCmd(String cmdLN)
               Scanner line = new Scanner(cmdLN);
               if (line.hasNext())
                    String cmd = line.next();
                    //What to do when users enter the various commands below.
                    if (cmd.equals("help"))
                         this.displayHelp();
                    else if (cmd.equals("Q!"))
                         this.done = true;
                    else if (cmd.equals("F") && line.hasNext())
                         this.inputFromFile(line.next());
                    else if (cmd.equals("K") && line.hasNext())
                         int numItemsToAdd = Integer.valueOf( line.next() ).intValue();
                         this.toAdd = numItemsToAdd;
                         this.inputFromKeyboard(numItemsToAdd);
          /**What to do if input comes from a file.
           *     @param inputFile; The name of the input file to process.*/
          private void inputFromFile(String inputFile)
               Scanner cin = new Scanner(System.in);
               System.out.println("!Using input file " + inputFile + ".");
               System.out.print("!Enter the name of the output file: ");
               String outputFile = cin.next();
               System.out.println("!Using output file " + outputFile + ".");
              try
                   BufferedReader in = new BufferedReader(new FileReader(inputFile));
                   //Scanner in = new Scanner(new File(inputFile));
                   //Initialize the String variables.
                   String line1 = null;
                   String line2 = null;
                   String line3 = null;
                   String line4 = null;
                   String line5 = null;
                   String line6 = null;
                   String line7 = null;
                   String line8 = null;
                   String line9 = null;
                   System.out.println(in.equals(",") + " see?");
                   //System.out.println((char)(char)in.read() + " experiment");
                   /**This loop assigns values to the string variables based on the
                    * values on each line in the input file. */
                   while(in.readLine() != null)
                        line1 = in.readLine();
                        line2 = in.readLine();
                        line3 = in.readLine();
                        line4 = in.readLine();
                        line5 = in.readLine();
                        line6 = in.readLine();
                        line7 = in.readLine();
                        line8 = in.readLine();
                        line9 = in.readLine();
                   //Print the contents of each line in the input file.
                   System.out.println("!value of line 1: " + line1);
                   System.out.println("!value of line 2: " + line2);
                   System.out.println("!value of line 3: " + line3);
                   System.out.println("!value of line 4: " + line4);
                   System.out.println("!value of line 5: " + line5);
                   System.out.println("!value of line 6: " + line6);
                   System.out.println("!value of line 7: " + line7);
                   System.out.println("!value of line 8: " + line8);
                   System.out.println("!value of line 9: " + line9);
                /**Add items to the warehouses.*/
                   warehouseAList.add(line1);
                   warehouseBList.add(line4);
                   warehouseCList.add(line7);
                /**Add the item count and total value for warehouse A.*/
                   int intLine2 = Integer.valueOf(line2).intValue();
                   this.intWarehouseAItemCount = intLine2;
                   double dblLine3 = Double.valueOf(line3).doubleValue();
                   this.dblTotalValueA = dblLine3;
                /**Add the item count and total value for warehouse B.*/
                   int intLine5 = Integer.valueOf(line5).intValue();
                   this.intWarehouseBItemCount = intLine5;
                   double dblLine6 = Double.valueOf(line6).doubleValue();
                   this.dblTotalValueB = dblLine6;
                /**Add the item count and total value for warehouse C.*/
                  int intLine8 = Integer.valueOf(line8).intValue();
                  this.intWarehouseCItemCount = intLine8;
                  double dblLine9 = Double.valueOf(line9).doubleValue();
                  this.dblTotalValueC = dblLine9;
                /**Ask the user how many items to add or delete from inventory.*/
                  System.out.print("Enter the number to add to inventory for " +
                                                               warehouseAList.get(0) + ":");
                  String toAddOrDel = cin.next();
                /**Print the contents of all the warehouses. */
                   System.out.println(" ");
                   //Print the contents of warehouse A.
                   System.out.println("!--------------------------------");
                   System.out.println("!----------Warehouse A:----------");
                   System.out.println("!--------------------------------");
                   //Print the item list for warehouse A.
                   System.out.println(warehouseAList);
                   //Print the total amount of items in warehouse A.
                   System.out.println("Total items: " + this.intWarehouseAItemCount);
                   //Print the total value of the items in warehouse A.
                   System.out.println("Total value: " + this.dblTotalValueA);
                   System.out.println("!--------------------------------");
                   System.out.println("!----------Warehouse B:----------");
                   System.out.println("!--------------------------------");
                   //Print the item list for warehouse B.
                   System.out.println("!warehouseB: " + warehouseBList);
                   //Print the total amount of items in warehouse B.
                   System.out.println("Total items: " + this.intWarehouseBItemCount);
                   //Print the total value of the items in warehouse B.
                   System.out.println("Total value: " + this.dblTotalValueB);
                   System.out.println("!--------------------------------");
                   System.out.println("!----------Warehouse C:----------");
                   System.out.println("!--------------------------------");
                   //Print the item list for warehouse C.
                   System.out.println("!warehouseC: " + warehouseCList);
                   //Print the total amount of items in warehouse C.
                   System.out.println("Total items: " + this.intWarehouseCItemCount);
                   //Print the total value of the items in warehouse C.
                   System.out.println("Total value: " + this.dblTotalValueC);
                   in.close();
              catch (FileNotFoundException e)
                   System.out.println("!Error: Unable to open file for reading.");
              catch (EOFException e)
                   System.out.println("!Error: EOF encountered, file may be corrupted.");
              catch (IOException e)
                   System.out.println("!Error: Cannot read from file.");
          /**What to do if input comes from the keyboard.
           *     @param numItems; The total number of items that will be added to the
           *                      Warehouse(s). */
          public void inputFromKeyboard(int numItems)
               System.out.println("!You will be adding " + numItems + " items to " +
                                             "inventory from the keyboard. ");
               this.toAdd = numItems;
               Scanner cin = new Scanner(System.in);
               //Prompt user for name of output file.
               System.out.print("!Enter the name of the output file: ");
               String outputFile = cin.next();
               /**This loop asks the user for information about the item(s) and inputs
                 *them into the appropriate array.*/
               int count = 0;
               while (numItems > count)
                    //Item name.
                    System.out.print("!Item name: ");
                    String addItemName = cin.next();
                    //Number in stock.
                    System.out.print("!Number in stock: ");
                    String addNumInStock = cin.next();
                    //Initial warehouse.
                    System.out.print("!Initial warehouse(A,B,C): ");
                    String addInitWarehouse = cin.next();
                    //Value of one item.
                    System.out.print("!Value of one item: ");
                    String addValueOfOneItem = cin.next();
                    //Add or delete from inventory
                    System.out.print("!Enter amount to add or delete from inventory: ");
                    String strAddOrDelete = cin.next();
                    System.out.println("!Amount to add or delete: " + strAddOrDelete);
                    //Cast
                    int intAddNumInStock = Integer.valueOf(addNumInStock).intValue();
                    double doubleAddValueOfOneItem = Double.valueOf(addValueOfOneItem).doubleValue();
                    int intAddOrDelete = Integer.valueOf(strAddOrDelete).intValue();
                    /**Add intAddNumInStock with intAddOrDelete to determine the amount
                     * to add or delete from inventory (If a user wishes to remove items
                     * from inventory simply add negative values). */
                    intAddNumInStock = intAddNumInStock + intAddOrDelete;
                    System.out.println("!Inventory after modifications: " + strAddOrDelete);
                    this.strItemName = addItemName;
                    this.intNumInStock = intAddNumInStock;
                    this.dblValueOfOneItem = doubleAddValueOfOneItem;
                    //Put items into warehouse A if appropriate.
                    if (intAddNumInStock < 25)
                        //Increment the warehouse A item count.
                        this.intWarehouseAItemCount = this.intWarehouseAItemCount + 1;
                        //Calculate the total value of warehouse A.
                        this.dblTotalValueA = this.dblTotalValueA + intAddNumInStock * doubleAddValueOfOneItem;
                        //Create the warehouse A array list.
                        this.createWareHouseA();
                    //Put items into warehouse B if appropriate.
                    if (intAddNumInStock >= 25)
                        if (intAddNumInStock < 75)
                             //Increment the warehouse B item count.
                             this.intWarehouseBItemCount = this.intWarehouseBItemCount + 1;
                             //Calculate the total value of warehouse B.
                             this.dblTotalValueB = this.dblTotalValueB + intAddNumInStock * doubleAddValueOfOneItem;
                             //Create the warehouse B array list.
                             this.createWareHouseB();
                    //Put items into warehouse C if appropriate.
                    if (intAddNumInStock >= 75)
                        //Increment the warehouse C item count.
                        this.intWarehouseCItemCount = this.intWarehouseCItemCount + 1;
                        //Calculate the total value of warehouse C.
                        this.dblTotalValueC = this.dblTotalValueC + intAddNumInStock * doubleAddValueOfOneItem;
                        //Create the warehouse C array list.
                        this.createWareHouseC();
                     //display helpful information.      
                    System.out.println("!--------------------------------");
                    System.out.println("!" + addItemName + " is the item name.");
                    System.out.println("!" + addNumInStock + " is the number in stock.");
                    System.out.println("!" + addInitWarehouse + " is the initial warehouse.");
                    System.out.println("!" + addValueOfOneItem + " is the value of one item.");
                    System.out.println("!--------------------------------------------------");
                   //Increment the counters.
                    count++;
               /**Create and write to the output file. */
               try
                     //Use the output file specified by the user.
                    PrintWriter out = new PrintWriter(outputFile);
                 /**Write warehouse A details.*/
                      //Blank the first line.
                      out.println(" ");
                    //Write the array list for warehouse A.
                    out.println(warehouseAList);
                    //Write the amount of items in warehouse A.
                    out.println(intWarehouseAItemCount);
                    //Write the total value for warehouse A.
                    out.println(dblTotalValueA);
                 /**Write warehosue B details.*/
                   //Write the array list for warehouse B.
                    out.println(warehouseBList);
                    //Write the amount of items in warehouse B.
                    out.println(intWarehouseBItemCount);
                    //Write the total value for warehouse B.
                    out.println(dblTotalValueB);
                 /**Write warehouse C details.*/
                      //Write the array list for warehouse C.
                    out.println(warehouseCList);
                    //Write the amount of items in warehouse C.
                    out.println(intWarehouseCItemCount);
                    //Write the total value for warehouse C.
                    out.println(dblTotalValueC);
                    //Close the output file.
                    out.close();     
                catch (FileNotFoundException e)
                   System.out.println("Error: Unable to open file for reading.");
               catch (IOException e)
                   System.out.println("Error: Cannot read from file.");
               /**View the contents and the value of each warehouse.*/
               System.out.println("!---------------Inventory Summary------------------");
               System.out.println("!--------------------------------------------------");
               System.out.println("!--------------------LEGEND:-----------------------");
               System.out.println("!<item type>, <amount in stock>,<value of one item>");
               System.out.println("!--------------------------------------------------");
               System.out.println("!------------------Warehouse A:--------------------");
               System.out.println("!--------------------------------------------------");
               //Display Items in warehouse A.
               System.out.println(warehouseAList);
               //Total items in warehouse A.
               System.out.println("Total items: " + intWarehouseAItemCount);
               //Display total value of warehouse A.
               System.out.println("Total value: " + "$" + dblTotalValueA);
               System.out.println("!--------------------------------------------------");
               System.out.println("!------------------Warehouse B:--------------------");
               System.out.println("!--------------------------------------------------");
               //Display Items in warehouse B.
               System.out.println(warehouseBList);
               //Total items in warehouse B.
               System.out.println("Total items: " + intWarehouseBItemCount);
               //Display total value of warehouse B.
               System.out.println("Total value: " + "$" + dblTotalValueB);
               System.out.println("!--------------------------------------------------");
               System.out.println("!------------------Warehouse C:--------------------");
               System.out.println("!--------------------------------------------------");
               //Display Items in warehouse C.
               System.out.println(warehouseCList);
               //Total items in warehouse C.
               System.out.println("Total items: " + intWarehouseCItemCount);
               //Display total value of warehouse C.
               System.out.println("Total value: " + "$" + dblTotalValueC);
         /**Display a help message.*/
         private void displayHelp()
              System.out.println("!--------------------------------");
              System.out.println("! General Help:");
              System.out.println("!--------------------------------");
              System.out.println("! ");
              System.out.println("!'help' display this help message.");
              System.out.println("!'Q!' quit this program.");
              System.out.println("!--------------------------------");
              System.out.println("! Input File Specific Commands:");
              System.out.println("!--------------------------------");
              System.out.println("! ");
              System.out.println("!'F' <name> type F followed by the name of the " +
                                       "file to be used for input.");
              System.out.println("!---------------------------------------");
              System.out.println("! Input From Keyboard Specific Commands:");
              System.out.println("!---------------------------------------");
              System.out.println("! ");
              System.out.println("!'K' <number> type K followed by the number of " +
                                        "items that will be added. ");
              System.out.println("! ");
    }Program file:
    public class InventoryProg
         public static void main(String[] args)
              //Create a new Inventory object.
              Inventory test = new Inventory();
              //Execute the command interpreter.
              test.cmdInterpreter();
    }Right now I am stuck on this and I cannot progress any further until I figure out how to input the data in the text file back into a arraylist.
    Thanks in advance.

    Thanks but I figured it out. Heres a sample of the code i used to solve my problem:
    try
                           //Warehouse A BufferedReader.
                   BufferedReader inA = new BufferedReader(new FileReader(inputFileWarehouseA));
                   //Warehouse B BufferedReader.
                   BufferedReader inB = new BufferedReader(new FileReader(inputFileWarehouseB));
                   //Warehouse C BufferedReader.
                   BufferedReader inC = new BufferedReader(new FileReader(inputFileWarehouseC));
                   //Warehouse details BufferedReader.
                   BufferedReader inDetails = new BufferedReader(new FileReader(inputFileDetails));
                   //Will hold values in warehouse arraylists.
                   String lineA = null;
                   String lineB = null;
                   String lineC = null;
                   //Will hold the details of each warehouse.
                   String line1 = null;
                   String line2 = null;
                   String line3 = null;
                   String line4 = null;
                   String line5 = null;
                   String line6 = null;
                   //Get the item count and total value for each warehouse.
                   while(inDetails.readLine() != null)
                        line1 = inDetails.readLine();
                        line2 = inDetails.readLine();
                        line3 = inDetails.readLine();
                        line4 = inDetails.readLine();
                        line5 = inDetails.readLine();
                        line6 = inDetails.readLine();
               /**Assign the item count and total value to warehouse A.*/
                  //Cast.
                   int intLine1 = Integer.valueOf(line1).intValue();
                   double dblLine2 = Double.valueOf(line2).doubleValue();
                   //Assign the values.
                   this.intWarehouseAItemCount = intLine1;
                   this.dblTotalValueA = dblLine2;
                /**Assign the item count and total value to warehouse B.*/
                     //Cast.
                   int intLine3 = Integer.valueOf(line3).intValue();
                   double dblLine4 = Double.valueOf(line4).doubleValue();
                     //Assign the values.
                   this.intWarehouseBItemCount = intLine3;
                   this.dblTotalValueB = dblLine4;
                /**Assign the item count and total value to warehouse C.*/
                     //Cast.
                     int intLine5 = Integer.valueOf(line5).intValue();
                   double dblLine6 = Double.valueOf(line6).doubleValue();
                   //Assign the values.
                   this.intWarehouseCItemCount = intLine5;
                   this.dblTotalValueC = dblLine6;
                /**Put the items back into the warehouses arraylists. */
                   //Add items to warehouse A.
                   while((lineA = inA.readLine()) != null)
                        warehouseAList.add(lineA);
                   //Add items to warehouse B.
                   while((lineB = inB.readLine()) != null)
                        warehouseBList.add(lineB);
                   //Add items to warehouse C.
                   while((lineC = inC.readLine()) != null)
                        warehouseCList.add(lineC);
                   }(this isn't the whole try statement its pretty long)

  • How to modify numbers in a arraylist?

    Say I have an arraylist with these values:
    [item1, 65, 555.5]item1 represents the name of an item type, 65 represents the number in stock, and 555.5 represents the value of one item.
    Now say I want to add 10 item1's to the number in stock. So I want to change the 65 in the array list to a 75. How could I do this?
    Thanks

    This would be a lot easier if you created a class to encapsulate those three data members, then created a list of those objects. The class could have three variables, name, stock, and value. Then it's easy to write a method to add or subract to the stock of a particular item, and you don't have to worry about modifying the wrong element in the list, casting elements to the right type (String, int, float, etc).
    public class Item {
        private String name;
        private int stock;
        private float value;
    }

  • 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

  • ArrayList and wrappers

    Can an ArrayList contain different types of objects from the same class?
    I know that it must be an object but can one be of type String and another be of type int?
    I am reading information from a file that looks something like this:
    Sam
    Jones
    21
    Tim
    Hendricks
    15
    I have written the following method:
    ArrayList list = new ArrayList();
    String fname;
    try
      BufferedReader br = new BufferedReader(new FileReader("student.txt"));
      while ((fname = br.readLine()) != null)
             String lname=br.readLine();
         int age= br.readLine();
         br.readLine(); //FOR THE BLANK LINE
         list.add(new Student(fname, lname, age));
      br.close();
    catch(IOException e)
      System.err.println(e.getMessage());
      System.exit(0);
    }If I declare age as type String the method and other methods work great, but I need to make it of type int.
    I have read up about wrappers and I think that is what I am suppose to use for the int but no matter what I do, I get tonnes of error messages.
    Any help would be appreciated.

    A better way would be to build a class for your data packet.
    class Thing {
      public final String name;
      public final int age;
      public Thing(String name, int age) {
        this.name = name;
        this.age = age;
    public class SomeClass {
      public static void main(String[] args) {
        List list = new ArrayList();
        list.add(new Thing("Jill",10));
        list.add(new Thing("John",20));
        list.add(new Thing("Janet",30));
        list.add(new Thing("Jeremy",40));
    }Then you can simply get your values back with
    for(Iterator iterator = list.iterator(); iterator.hasNext(); ) {
      Thing thing = (Thing) iterator.next();
      System.out.println("Name: "+thing.name);
      System.out.println("Age: "+thing.age);
    }Or something like that...
    Talden

Maybe you are looking for

  • External hard drive no longer shows up connected

    I have been using a Seagate Freeagent 500 GB external HD as a backup storage device for my Windows 7, 64 bit computer. After working well for several years it did not respond the last time I tried to back up and shows up as "disconnected" when I sear

  • Trying to use Crystal Reports XI Release 2  to display a report

    I am creating an application in Visual Basic using Microsoft Visual Studio 2005.  I have downloaded the trial version of Crystal Reports XI and I have built my report and have attached to the Crystal Viewer that is on my form in my application.  I us

  • Customer Clearing Error

    When f-44 posting ,system showing error messege: crest transaction type is missing

  • Configuration could not be verified error when connect to Cox

    Hi, I'm trying to connect to Cox but keep getting the "configuration could not be verified" error. I can access my Cox account through web mail and I've retyped and retried my email address and password enough times to be confident that it's correct.

  • How to reject the zip from zip drive

    Hello to all! I have an apple g4 powermac quicksilver with an zip 250 drive. How do i reject the zip disc because the button for reject the zip disc lies behind the front? Best regards and have a nice weekend!!! Chuck