Printing an ArrayList

Hi there,
I need a little bit of help to print some text. I am able to print out a simple line of text and it works fine, but I need to be able to print out the contents of an ArrayList. At the moment I have a Page() class that implements Prinatable. By default there is a print() mehtod. In htis print method is where I set my page size and also the text that need to be printed. The method
g2d.drawString(titleText, (int) titleX, (int) titleY);is the method that actually prints the text. titleText is just a regular String.
If I want to print the contents of an ArrayList I'll have to iterate over it somehow and extract he data that I want to print.
The method g2d.drawString() can take an argument AttributedCharacterIterator instead of string and it will iterate over this and print out what is in it.
Is there anyway I can add the data in my ArrayList to the AttributedCharacterIterator? Because I tried to iterate through my ArrayList and add iter.next() to AttributedCharacterIterator but I get a classCastExcetpion.
It would be great to hear from anyone who has printed from an Arraylist before. I have posted the code form my Page() class below.
Thanks,
Chris
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex)
throws PrinterException {
Graphics2D g2d = (Graphics2D) graphics;
g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
g2d.setPaint(Color.black);
String titleText = "E-vote Ballot";
Font titleFont = new Font("tahoma", Font.BOLD, 36);
FontMetrics fontMetrics = g2d.getFontMetrics ();
double titleX = (pageFormat.getImageableWidth () / 2) - (fontMetrics.stringWidth (titleText) / 2);
double titleY = 3 * POINTS_PER_INCH;
g2d.drawString(titleText, (int) titleX, (int) titleY);
return (PAGE_EXISTS);
}

I need to be able to print out the contents of an ArrayListDo you want all the items together or each item on it's own line?
for the former,
* returns a String containing al's elements, space-separated.
String arrayListToString( ArrayList al )
   String s = "";
   for (Object o :  al)
      s += o + " ";
   s = s.substring(0,s.length() - 1); // cut off that last space we added
   return s;
}and then
g2d.drawString(arrayListToString( yourList ), posX, posY); for the latter,
* Draws the elements of al to the screen as strings.  The first element goes at
* posX , posY, the second goes at  posX, posY + vertOffset,  &c
void drawArrayList( ArrayList al , Graphics g , int posX, int posY, int vertOffset)
   int offset = 0;
   for (Object o : al)
      g.drawString( o, posX  , posY + offset);
      offset += vertOffset;
}

Similar Messages

  • Help reading .csv file into an arraylist

    i need to read a csv file into an arraylist and then print the arraylist to the screen.
    using:
    try {
                // Setup our scanner to read the file at the path c:\test.txt
                Scanner myscanner = new Scanner(new File("\\carsDB.csv"));    
    ArrayList<CarsClass> carsClass = new ArrayList<CarsClass>(" write all fields");   
                while (myscanner.hasNextLine()) {
    myscanner.add(" add car fields to the carClass");              // Write your code here.
    // loop to read them all to the screencsv file is like this:
    Manufacturer,carline name,displ,cyl,fuel,(miles),Class
    CHEVROLET,CAVALIER (natural gas),2.2,4,CNG,120,SUBCOMPACT CARS
    HONDA,CIVIC GX (natural gas),1.6,4,CNG,190,SUBCOMPACT CARS
    FORD,CONTOUR (natural gas),2,4,CNG,70,COMPACT
    FORD,CROWN VICTORIA (natural gas),4.6,8,CNG,140/210*,LARGE CARS
    FORD,F150 PICKUP (natural gas) - 2WD,5.4,8,CNG,130,STANDARD PICKUP TRUCKS 2WD
    FORD,F250 PICKUP (natural gas) - 2WD,5.4,8,CNG,160,STANDARD PICKUP TRUCKS 2WD
    FORD,F250 PICKUP (natural gas) - 2WD,5.4,8,CNG,150/210*,STANDARD PICKUP TRUCKS 2WD
    FORD,F150 PICKUP (natural gas) - 4WD,5.4,8,CNG,130,STANDARD PICKUP TRUCKS 4WD
    FORD,F250 PICKUP (natural gas) - 4WD,5.4,8,CNG,160,STANDARD PICKUP TRUCKS 4WD
    FORD,E250 ECONOLINE (natural gas) - 2WD,5.4,8,CNG,170,"VANS, CARGO TYPE"
    FORD,E250 ECONOLINE (natural gas) - 2WD,5.4,8,CNG,80,"VANS, CARGO TYPE"
    FORD,F150 LPG - 2WD,5.4,8,LPG,290/370*,STANDARD PICKUP TRUCKS 2WD
    FORD,F250 LPG - 2WD,5.4,8,LPG,260/290/370**,STANDARD PICKUP TRUCKS 2WD
    ok, so do i need to write a file carsclass.java or is the line:
    ArrayList<CarsClass> carsClass = new ArrayList<CarsClass>(" write all fields");
    going to define my carsclass objects? how do i write my fields for each of the 7 categories?
    i believe i can easily add to and print the arraylist, but i'm confused how to go about creating this arraylist in the first place. do i just create carclass.java and save them all as strings? i guess my question is mainly how should i structure this? any suggestions/help is appreciated.
    Edited by: scottc on Nov 15, 2007 5:55 PM

    String.split uses regular expressions.Ahh yeah ummm (slaps forehead) I'd forgotten that... so maybe StringTokeniser is more accessible for noob's. Sorry.
    Anyway... if all you want/need to so is store a bunch of String field values then how about using an array of String's instead of individual fields... maybe something like:
    forums\Car.java
    * Car Data Transfer Object. All fields are final, making objects of this class
    * thread safe(r).
    * @author keith
    package forums;
    import krc.utilz.stringz.Arrayz;
    public class Car
      // class attributes                       // variables //isn't actually wrong, it's just not quit right.
      private final String[] fields;            // final means values are write once, read many times, which is thread safe(r).
       * Initialises the new Cars fields to the given fields array.
       * @param fields - an array of any (reasonable) length
      public Car(String[] fields) {             // no need to comment a constructor as a constructor.
        this.fields = fields;                   // much better to provide javadoc comments explaining
      }                                         // what the method does and how to use it.
       * Returns this Car's fields as one long string.
      public String toString() {                // It's actually GOOD to be a lazy programmer.
        return Arrayz.join(", ", this.fields);  // I have reused my Arrayz.join in several projects.
                                                // I think you can use Array.toString (new in 1.6) instead.
    krc\utilz\stringz\Arrayz.java
    package krc.utilz.stringz;
    import java.util.List;
    import java.util.ArrayList;
    public class Arrayz
        * returns true if the given value is in the args list, else false.
        * @param value - the value to seek
        * @param args... - variable number of String arguments to look in
      public static boolean in(String value, String... args) {
        for(String a : args) if(value.equals(a)) return true;
        return false;
        * append the elements of array into one string, seperated by FS
        * @param a  - an array of strings to join together
        * @param FS - Field Seperator string, optional default=" "
        * @example
        *  String[] array = {"Bob","The","Builder"};
        *  System.out.println(join(array);
        *  --> Bob The Builder
        *  System.out.println("String[] array = {\""+join(array, "\",\"")+"\"};");
        *  --> String[] array = {"Bob","The","Builder"};
      public static String join(String FS, String[]... arrays) {
        StringBuffer sb = new StringBuffer();
        for (String[] array : arrays)
          sb.append(join(array, FS));
        return(sb.toString());
      public static String join(String[] array) {
        return(join(array, " "));
      public static String join(String[] a, String FS) {
        if (a==null) return null;
        if (a.length==0) return "";
        StringBuffer sb = new StringBuffer(a[0]);
        for (int i=1; i<a.length; i++) {
          sb.append(FS+a);
    return sb.toString();
    * append all the elements of the given arrays into one big array
    * @param String[]... arrays - to be concatenated
    * @return String[] - one big array
    public static String[] concatenate(String[]... arrays) {
    List<String> list = new ArrayList<String>();
    for(String[] array : arrays) {
    for(String item : array) {
    list.add(item);
    return(list.toArray(new String[0]));
    I guess that Arrayz class might be a bit beyond you at the moment so don't worry too much if you can't understand the code... there are no nasty surprises in it... just cut and paste the code, change the package name, and use it (for now).

  • File (Directory) object problem?

    Hi there. My problem is as follows. The method below is supposed to access an pre-existing directory with five previously saved test files, read in those files as account objects, add the objects to an ArrayList, then return the ArrayList. It seems to be able to create a file object representing the directory alright but it then insists that there are no files in the directory! Have I fouled up or is there some subtlety that I'm unware of? I was wondering if the fact that the account files have a .bac extenstion had something to do with it.
    Here's the method, with the two lines of code where I think the problem might lie in bold print:
    public ArrayList retrieveAccounts()throws IOException{
    ArrayList accounts = new ArrayList();
    File accDir = new File("C:" + File.separator + "accounts"); //creates a directory object
    //The following S.o.p statements are for test and maintenance purposes rather than user feedback
    System.out.println("Directory " + accDir.getCanonicalPath() + " opened");
    System.out.println("Confirm Accounts directory exists: " + accDir.exists());
    System.out.println("Directory: " + accDir.isDirectory());
    String [] accFiles = accDir.list(); //gets a list of files in the directory and saves it as a String array
    System.out.println("Number of files in directory: " + accDir.length());
    while(i < accDir.length()){
    filename = accFiles;
    try{
    //open layered input Streams to access the next account file in line
    ObjectInputStream in = new ObjectInputStream(new FileInputStream("C:"+ File.separator + "accounts" + File.separator + filename));
    account = (Account)in.readObject();
    accounts.add(account);
    in.close(); //closes Streams for that particular file
    }catch(IOException e){System.out.println("Filing error as follows: " + e);
                }catch(ClassNotFoundException e){System.out.println("Class not Found. Details: " + e); }
    filename = null; //frees up reference for next file
    i++;//counter increments by one
    return accounts;

    This is what I was trying to do minus the comments and maintence and test code:
    public ArrayList retrieveAccounts()throws IOException{
    ArrayList accounts = new ArrayList();
    File accDir = new File("C:" + File.separator + "accounts");
    String [] accFiles = accDir.list();
    while(i < accDir.length()){
    filename = accFiles;
    try{
    ObjectInputStream in = new ObjectInputStream(new FileInputStream("C:"+ File.separator + "accounts" + File.separator + filename));
    account = (Account)in.readObject();
    accounts.add(account);
    in.close();
    }catch(IOException e){System.out.println("Filing error as follows: " + e);
    }catch(ClassNotFoundException e){System.out.println("Class not Found. Details: " + e); }
    filename = null;
    i++;
    return accounts;
    By the way, your the first Java programmer that I've met that doesn't like comments! :)
    NOTE: Think I may have spotted where I went wrong in my code.
    filename = accFiles;
    Forgot to point it at the specific element of the array, like so:
    filename = accFiles[i];
    Thanks for your help!

  • Formating table using c:forEach

    Dear fellow Java Developers,
    I have an object in session called grid whose properties consist of several array lists. I am trying to iterate through each ArrayList so that each list has its own column side by side in one HTML table. Currently the page displays the data but does not build the table correctley. I am having a lot of trouble correctly building the HTML table. Here is my JSP code:
    <table border="1">
         <c:forEach var="cusID" items="${grid.cusID}">
         <tr>
              <td>
                   <c:out value="${cusID}" />
              </td>
         </c:forEach>     
         <c:forEach var="cusName" items="${grid.cusName}">
              <td>
                   <c:out value="${cusName}" />
              </td>
         </tr>
         </c:forEach>
    </table>The CusID and CusName are printed in one long column rather then having a table with two columns side by side as desired.
    Could anyone show me a JSP code example which prints two ArrayLists in seperate columns of a HTML table?
    many thanks in advance to anyone who replies,
    James.

    Lemme see if I understand correctly...
    You have a grid object, with two ArrayLists, cusID and cusName. You want to print a table that looks like this:
    |    cusID[0]    |    cusName[0]    |
    |    cusID[1]    |    cusName[1]    |
    //...My approach would be to redesign your grid to contain a single ArrayList of Customers, which would be a simple JavaBean, like this:
    package beans;
    private String id, name;
    public class Customer implements java.io.Serializable
      public Customer();
      public void  setId(String _id) { id = _id; }
      public void setName(String _name) { name = _name; }
      public String getId() { return id; }
      public String getName() { return name; }
    }Then change your grid to use the Customer bean to store customer IDs and Names in a single array list (named customers) with an appropriate get method... then you could do:
    <table border="1">
         <c:forEach var="customer" items="${grid.customers}">
         <tr>
              <td><c:out value="${customer.id}" /></td>
              <td><c:out value="${customer.name}" /></td>
         </tr>
         </c:forEach>
    </table>

  • How would i create this

    Hello
    I am required to make a program with a loop which records new records broken at a carnival. Someone will input the new record and holder and when the loop is ended it will display all the records, like a printout.
    I'm fairly new to java, is there anyway this can easily be done?
    Thanks

    I have this so far
    import java.util.ArrayList;
    public class Person
        public static void main (String[] args)
                int print = 0;
                ArrayList alist1 = new ArrayList();
                //loop here
            System.out.print ("Enter a record");
    }I dont know what loop to use and how to use the array list, i have read it i just quite dont get it
    Message was edited by:
    Mike334

  • Getting an object from HttpSession...

    Hi all,
    I am stuck which is according to me is very obvious...please correct me if I am wrong.
    I have a java.util.ArrayList object in my HttpSession object.
    Now in my helper class to which the request is passed from the servlet I am extracting this ArrayList object in one ArrayList object and putting it into the HashMap. After this, I am again extracting this ArrayList object from the HttpSession and assigning it to a newly created ArrayList object in my helper class. Now I am passing this newly created ArrayList object to a method. This method after processing changes this ArrayList object. And finally I am putting this changed ArrayList object in the HashMap I created earlier.
    After doing all this, when I am trying to extract and print these ArrayList Objects from the session object...I found my first ArrayList object has also been affected by the same change as the second one. The expected result was only the second object will be changed. I am stuck with this.
    I know it has something to do with references....but I am not able to understand that when I am trying to create two new copies by extracting an object from the Session...and changing one how is my second object getting affected. Any help will be appriciated.
    The code for this is as follows:
    "phSessionState" is a collection object in HttpSession which holds all the other objects. We are not putting different objects directly in the HttpSession.
    "LineObject" is a simple JavaBean kind of class with gettrs and setters
    ArrayList originalList = (ArrayList)phSessionState.getData("lineObjectList");
    HashMap stagedLineObjects = new HashMap();
    stagedLineObjects.put("OriginalList", originalList);
    //Extracting same in another object and calling a method to update it.
    ArrayList tempList = (ArrayList)phSessionState.getData("lineObjectList");
    //Method to update the ArrayList
    updateLineObjectList(tempList, request);
    stagedLineObjects.put("UpdatedList", tempList);
    //Trying to get the objects from the HashMap and print
    System.out.println("Retriving OriginalList...");
    ArrayList List1 = (ArrayList)stagedLineObjects.get("OriginalList");
    for(int i=0; i<List1.size(); i++)
         LineObject lo = (LineObject)List1.get(i);
         System.out.println(lo.getUserID() + "\t" + lo.getPassword()
    + "\t" + lo.getFirstName() + "\t" + lo.getMiddleName() + "\t" +
    lo.getLastName());
    System.out.println("Retriving UpdatedList...");
    ArrayList List2 = (ArrayList)stagedLineObjects.get("UpdatedList");
    for(int i=0; i<List2.size(); i++)
         LineObject lo = (LineObject)List2.get(i);
         System.out.println(lo.getUserID() + "\t" + lo.getPassword()
    + "\t" + lo.getFirstName() + "\t" + lo.getMiddleName() + "\t" +
    lo.getLastName());
    Waiting for your valuable help...
    Thanks & Regards,
    Gauz

    You must remember that objects are passed by reference. So when you are passing around your ArrayList, you are actually passing a reference to the ArrayList. In other words, there exists one instance of your specific ArrayList in memory and what you are passing around are copies of the "reference" to that memory location.
    If you want to pass a copy of your ArrayList, you can create a copy of the ArrayList and pass the reference to that new copy. One way to do this is as follows:ArrayList originalList = new ArrayList();
    //Let's put two objects into the ArrayList
    originalList.add(1, new StringBuffer("object1"));
    originalList.add(2, new StringBuffer("object2"));
    //Now let's copy the ArrayList
    ArrayList copyOfList = new ArrayList(originalList);
    //now, you have two copies of the ArrayList.  You can make
    //changes to copyOfList without affecting originalList
    copyOfList.add(3, new StringBuffer("object3"));
    //Checking the size of each ArrayList will demonstrate a difference
    System.out.println("Original's size is " + originalList.size());
    System.out.println("Copy's size is " + copyOfList.size());
    //Output should be:
    //  Original's size is 2
    //  Copy's size is 3Please keep in mind that the objects within the ArrayList are also being passed by reference. So if you modify an object within originalList, those modifications will be reflected in the same object found in copyOfList.
    For example,StringBuffer sb = (StringBuffer)copyOfList.get(1);
    sb.append(":modified");
    //Now print the values of the first object in each ArrayList
    StringBuffer sbFromOriginal = (StringBuffer)originalList.get(1);
    StringBuffer sbFromCopy = (StringBuffer)copyOfList.get(1);
    System.out.println("Original's value is " + sbFromOriginal.toString());
    System.out.println("Copy's value is " + sbFromCopy.toString());
    //Your output should read
    //  Original's value is object1:modified
    //  Copy's value is object1:modifiedThis is because you made a copy of the ArrayList, but not a copy of each object within the ArrayList. So you actually have two seperate copies of ArrayList but they are referencing the same two objects in positions 1 and 2. The object in position 3 exists only in copyOfList.
    Hope this helps.

  • A code question

    Hi am just wondering if my break up of this code is correct for the time being , I have two fields created string Name and string Number ?
    this I have a constructor which initiates the sting number and the string name then I have 2 return methods , is this correct so far ?
    Now in the second class I have defined an array list which can output values which will give me more fluency ?
    I have defined the arraylist to messages in the constructer ,
    I was wondering if my perception of this code is right and if any body else has a better way of describing to me what is happening here I would be greatful ,
    also what are the main 4 thing you can add before the array Like the add funtion ?
    public class TelephoneEntry
    private String Name;
    private String Number;
    public TelephoneEntry(String Name ,String Number)
    this.Name = Name ;
    this.Number = Number ;
    public String getName()
    return Name;
    public String getNumber()
    return Number;
    import java.util.ArrayList ;
    public class TelephoneDirectory
         private ArrayList messages;
         public TelephoneDirectory()
              messages = new ArrayList();
         public void post(TelephoneDirectory item)
    messages.add(item);

    sorry my pardon the telephone dir class is printing an arraylist which lets the user search for as mnay people as it wants however the post method had it refering to its own class and as pointed out it needed to refer to the telephone entry class ,
    it will just search the telephoneentry I have not finished as I still need to work on the print statment in the public void post I am a little stuck actually to as how I am going to go about using this print statement again help is apprahictaed

  • Help on using hashtables with sub structures inside

    Hi everyone,
    I'm currently working on a script that scans Active Directory for computers, and lists current users logged, and logs to an hashtable the username as key, and a count as a value.
    After that it sends an email with the list. This part is all developed and working. Now I want to go further, and in the hash table, I would like to have as the key the username, and as the value the counter and a list of the computer names where the user
    is logged on.
    I have this code for working with the hashtable:
    ForEach ($c in $computer) {
    #Get explorer.exe processes
    $proc = gwmi win32_process -computer $c -Filter "Name = 'explorer.exe'"
    #Go through collection of processes
    ForEach ($p in $proc) {
    $temp = "" | Select Computer, Domain, User
    $temp.computer = $c
    $temp.user = ($p.GetOwner()).User
    $temp.domain = ($p.GetOwner()).Domain
    $report += $temp
    If($UsersList.ContainsKey($temp.user) -eq 1){
    $UsersList[$temp.user] = $UsersList[$temp.user] + 1
    #$UsersList
    Else {
    $UsersList.add($temp.user,1)
    Can I have it the way I'd like, or have to change my approach?
    Thanks in advance
    Nuno Silva

    Thanks for the help. One more question regarding printing the arraylist.
    I use the code below to print everything. I can print successfully the key and value but get an error on the computerlist.
    ($UsersList.GetEnumerator() |
    Sort-Object Value -descending |
    % { "{0}, {1} - {3}" -f $_.key, $_.value.Count, $_.value.ComputerList })
    Error formatting a string: Index (zero based) must be greater than or equal to zero and less than the size of the argument list..
    +     % { "{0}, {1} - {3}" -f $_.key, $_.value.Count, $_.value.ComputerList[0] })
    +         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidOperation: ({0}, {1} - {3}:String) [], RuntimeException
        + FullyQualifiedErrorId : FormatError
    Error formatting a string: Index (zero based) must be greater than or equal to zero and less than the size of the argument list..
    How can I print it out?
    Thanks in advance,
    Nuno Silva

  • New to Applets: Problems wiht writing to files and with scroll panes.

    Hi, I've recently graduated from university and so I have limited experience in java programming and I'm having some trouble with JApplets (this is the first time I've made one). I'm trying to make a simple program that will allow users to pick one of a few background images from a list (a list of jpanels within a scroll pane) then at the click of a button will output a CSS with the background tag set to the image location. This is for use on a microsoft sharepoint site where each user has a My-Sit area which I want to be customizable.
    So far I've been creating this program as an application rather than a JApplet and just having another class that extends the JApplet Class which then displays the JFrame from the GUI Class. This initially didnt work because I was trying to add a window to a container so I kept programming it as an application until I got it working before trying to convert it to a JApplet. I solved the previous problem by changing my GUI class to extend JPanel instead of JFrame and it now displays correctly but with a coupe of issues.
    Firstly the applet will not create/write to the CSS file. I read that applets couldnt read/write to the users file system but they could to their own. The file I wish to write to is kept on the same machine as the applet so I'm not sure why this isn't working.
    Secondly the scroll panel is no longer working properly. This worked fine when I was still running the program as an application when the GUI still extended JFrame instead of JPanel (incidentally the program no longer runs as an application in this state) but now the scroll bar does not appear. This is a problem since I want the applet to remain the same size on the page even if I decide to add more backgrounds to the list. I tried setting the applet height/width to smaller values in the html file to see if the scroll bar would appear if the area was smaller than the GUI should be, but this just meant the bottom off the applet was cut off.
    Could anyone offer any suggestion as to why these thigns arnt working and how to fix them? If necessary I can post my source code here. Thanks in advance.

    Ok, well my program is made up of 4 classes, I hope this isnt too much to be posting. If any explaination is needed then I'll post that next. Theres lots of print lines scattered aroudn due to me trying to fix this and theres some stuff commented out from when the program used to be an application isntead of an applet.
    GUI Class, this was the main class until I made a JApplet Class
    public class AppletGUI extends JPanel{
        *GUI Components*
        //JFrames
        JFrame mainGUIFrame = new JFrame();
        JFrame changeBackgroundFrame = new JFrame();
        //JPanels (Sub-panels are indented)
        JPanel changeBackgroundJP = new JPanel(new BorderLayout());
            JPanel changeBackgroundBottomJP = new JPanel(new GridLayout(1,2));
        JPanel backgroundJP = new JPanel(new GridLayout(1,2));
        JPanel selectBackground = new JPanel(new GridLayout(1,2));
        //Jbuttons
        JButton changeBackgroundJB = new JButton("Change Background");
        JButton defaultStyleJB = new JButton("Reset Style");
        //JLabels
        JLabel changeBackgroundJL = new JLabel("Choose a Background from the Menu");
        JLabel backgroundJL = new JLabel();
        //JScrollPane
        JScrollPane backgroundList = new JScrollPane();
            JPanel backgroundListPanel = new JPanel(new GridLayout());
        //Action Listeners
        ButtonListener bttnLstnr = new ButtonListener();
        //Controllers
        CSSGenerator cssGenerator = new CSSGenerator();
        Backgrounds backgroundsController = new Backgrounds();
        backgroundMouseListener bgMouseListener = new backgroundMouseListener();
        //Flags
        Component selectedComponent = null;
        *Colour Changer*
        //this method is used to change the colour of a selected JP
        //selected JPs have their background darkered and when a
        //different JP is selected the previously seleced JP has its
        //colour changed back to it's original.
        public void changeColour(JPanel theJPanel, boolean isDarker){
        //set selected JP to a different colour
        Color tempColor = theJPanel.getBackground();
            if(isDarker){
                tempColor = tempColor.darker();
            else{
                tempColor = tempColor.brighter();
            theJPanel.setBackground(tempColor);
         //also find any sub-JPs and change their colour to match
         int j = theJPanel.getComponents().length;
         for(int i = 0; i < j; i++){
                String componentType = theJPanel.getComponent(i).getClass().getSimpleName();
                if(componentType.equals("JPanel")){
                    theJPanel.getComponent(i).setBackground(tempColor);
        *Populating the GUI*
        //backgroundList.add();
        //Populating the Backgrounds List
        *Set Component Size Method*
        public void setComponentSize(Component component, int width, int height){
        Dimension tempSize = new Dimension(width, height);
        component.setSize(tempSize);
        component.setMinimumSize(tempSize);
        component.setPreferredSize(tempSize);
        component.setMaximumSize(tempSize);     
        *Constructor*
        public AppletGUI() {
            //REMOVED CODE
            //AppletGUI.setDefaultLookAndFeelDecorated(true);
            //Component Sizes
            //setComponentSize
            //Adding Action Listeners to Components
            System.out.println("adding actions listeners to components");
            changeBackgroundJB.addActionListener(bttnLstnr);
            defaultStyleJB.addActionListener(bttnLstnr);
            //Populating the Change Background Menu
            System.out.println("Populating the window");
            backgroundsController.populateBackgroundsData();
            backgroundsController.populateBackgroundsList();
            //loops to add background panels to the JSP
            ArrayList<JPanel> tempBackgroundsList = new ArrayList<JPanel>();
            JPanel tempBGJP = new JPanel();
            tempBackgroundsList = backgroundsController.getBackgroundsList();
            int j = tempBackgroundsList.size();
            JPanel backgroundListPanel = new JPanel(new GridLayout(j,1));
            for(int i = 0; i < j; i++){
                tempBGJP = tempBackgroundsList.get(i);
                System.out.println("Adding to the JSP: " + tempBGJP.getName());
                //Add Mouse Listener
                tempBGJP.addMouseListener(bgMouseListener);
                backgroundListPanel.add(tempBGJP, i);
            //set viewpoing
            backgroundList.setViewportView(backgroundListPanel);
            /*TESTING
            System.out.println("\n\n TESTING!\n Printing Content of SCROLL PANE \n");
            j = tempBackgroundsList.size();
            for(int i = 0; i < j; i++){
                System.out.println(backgroundList.getComponent(i).getName());
            changeBackgroundJP.add(changeBackgroundJL, BorderLayout.NORTH);
            changeBackgroundJP.add(backgroundList, BorderLayout.CENTER);
            //changeBackgroundJP.add(tempBGJP, BorderLayout.CENTER);
            changeBackgroundJP.add(changeBackgroundBottomJP, BorderLayout.SOUTH);
            changeBackgroundBottomJP.add(changeBackgroundJB);
            changeBackgroundBottomJP.add(defaultStyleJB);
            System.out.println("Finsihed populating");
            //REMOVED CODE
            //adding the Background Menu to the GUI and settign the GUI options
            //AppletGUI.setDefaultLookAndFeelDecorated(true);
            //this.setResizable(true);
            //this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            this.setLocation(500,500);
            this.setSize(400,300);
            this.add(changeBackgroundJP);
        //REMOVED CODE
         *Main Method*
        public static void main(String[] args){
           System.out.println("Creating GUI");
           AppletGUI theGUI = new AppletGUI();
           theGUI.setVisible(true);
           System.out.println("GUI Displayed");
         *Button Listener Inner Class*
        public class ButtonListener implements ActionListener{
            //check which button is clicked
            public void actionPerformed(ActionEvent event) {
                AbstractButton theButton = (AbstractButton)event.getSource();
                //Default Style Button
                if(theButton == defaultStyleJB){
                    System.out.println("Default Style Button Clicked!");
                //Change Background Button
                if(theButton == changeBackgroundJB){
                    System.out.println("Change Background Button Clicked!");
                    String backgroundURL = cssGenerator.getBackground();
                    if(backgroundURL != ""){
                        cssGenerator.setBackgroundChanged(true);
                        cssGenerator.setBackground(backgroundURL);
                        cssGenerator.outputCSSFile();
                        System.out.println("Backgroudn Changed, CSS File Written");
                    else{
                        System.out.println("No Background Selected");
         *Mouse Listener Inner Class*
        public class backgroundMouseListener implements MouseListener{
            public void mouseClicked(MouseEvent e){
                //get component
                JPanel tempBackgroundJP = new JPanel();
                tempBackgroundJP = (JPanel)e.getComponent();
                System.out.println("Background Panel Clicked");
                //change component colour
                if(selectedComponent == null){
                    selectedComponent = tempBackgroundJP;
                else{
                    changeColour((JPanel)selectedComponent, false);
                    selectedComponent = tempBackgroundJP;
                changeColour((JPanel)selectedComponent, true);
                //set background URL
                cssGenerator.setBackground(tempBackgroundJP.getName());
            public void mousePressed(MouseEvent e){
            public void mouseReleased(MouseEvent e){
            public void mouseEntered(MouseEvent e){
            public void mouseExited(MouseEvent e){
    }JApplet Class, this is what I plugged the GUI into after I made the change from Application to JApplet.
    public class AppletTest extends JApplet{
        public void init() { 
            System.out.println("Creating GUI");
            AppletGUI theGUI = new AppletGUI();
            theGUI.setVisible(true);
            Container content = getContentPane();
            content.setBackground(Color.white);
            content.setLayout(new FlowLayout());
            content.add(theGUI);
            AppletGUI theGUI = new AppletGUI();
            theGUI.setVisible(true);
            setContentPane(theGUI);
            System.out.println("GUI Displayed");
        public static void main(String[] args){
            AppletTest at = new AppletTest();
            at.init();
            at.start();
    }The CSS Generator Class. This exists because once I have the basic program working I intend to expand upon it and add multiple tabs to the GUI, each one allowing the user to change different style options. Each style option to be changed will be changed wit ha different method in this class.
    public class CSSGenerator {
        //Variables
        String background = "";
        ArrayList<String> backgroundCSS;
        //Flags
        boolean backgroundChanged = false;
        //Sets and Gets
        //For Variables
        public void setBackground(String theBackground){
            background = theBackground;
        public String getBackground(){
            return background;
        //For Flags
        public void setBackgroundChanged(boolean isBackgroundChanged){
            backgroundChanged = isBackgroundChanged;
        public boolean getBackgroundChanged(){
            return backgroundChanged;
        //background generator
        public ArrayList<String> backgroundGenerator(String backgroundURL){
            //get the URL for the background
            backgroundURL = background;
            //creat a new array list of strings
            ArrayList<String> backgroundCSS = new ArrayList<String>();
            //add the strings for the background options to the array list
            backgroundCSS.add("body");
            backgroundCSS.add("{");
            backgroundCSS.add("background-image: url(" + backgroundURL + ");");
            backgroundCSS.add("background-color: #ff0000");
            backgroundCSS.add("}");
            return backgroundCSS;
        //Write CSS to File
        public void outputCSSFile(){
            try{
                //Create CSS file
                System.out.print("creating file");
                FileWriter cssWriter = new FileWriter("C:/Documents and Settings/Gwilym/My Documents/Applet Data/CustomStyle.css");
                System.out.print("file created");
                System.out.print("creating buffered writer");
                BufferedWriter out = new BufferedWriter(cssWriter);
                System.out.print("buffered writer created");
                //check which settings have been changed
                //check background flag
                if(getBackgroundChanged() == true){
                    System.out.print("retrieving arraylist");
                    ArrayList<String> tempBGOptions = backgroundGenerator(getBackground());
                    System.out.print("arraylist retrieved");
                    int j = tempBGOptions.size();
                    for(int i = 0; i < j ; i++){
                        System.out.print("writing to the file");
                        out.write(tempBGOptions.get(i));
                        out.newLine();
                        System.out.print("written to the file");
                out.close();
            }catch (Exception e){//Catch exception if any
                System.out.println("Error: Failed to write CSS file");
        /** Creates a new instance of CSSGenerator */
        public CSSGenerator() {
    }The Backgrounds Class. This class exists because I didnt want there to just be a hardcoded lsit of backgrounds, I wanted it to be possible to add new ones to the list without simply lettign users upload their own images (since the intended users are kids and this sharepoint site is used for educational purposes, I dont want them uplaoded inapropraite backgrounds) but I do want the site admin to be able to add more images to the list. for this reason the backgrounds are taken from a list in a text file that will be stored in the same location as the applet, the file specifies the background name, where it is stored, and where a thumbnail image is stored.
    public class Backgrounds {
        //Array Lists
        private ArrayList<JPanel> backgroundsList;
        private ArrayList<String> backgroundsData;
        //Set And Get Methods
        public ArrayList getBackgroundsList(){
            return backgroundsList;
        //ArrayList Population Methods
        public void populateBackgroundsData(){
            //decalre the input streams and create a new fiel hat points to the BackgroundsData file
            File backgroundsDataFile = new File("C:/Documents and Settings/Gwilym/My Documents/Applet Data/BackgroundsData.txt");
            FileInputStream backgroundsFIS = null;
            BufferedInputStream backgroundsBIS = null;
            DataInputStream backgroundsDIS = null;
            try {
                backgroundsFIS = new FileInputStream(backgroundsDataFile);
                backgroundsBIS = new BufferedInputStream(backgroundsFIS);
                backgroundsDIS = new DataInputStream(backgroundsBIS);
                backgroundsData = new ArrayList<String>();
                String inputtedData = null;
                //loops until it reaches the end of the file
                while (backgroundsDIS.available() != 0) {
                    //reads in the data to be stored in an array list
                    inputtedData = backgroundsDIS.readLine();
                    backgroundsData.add(inputtedData);
            //TESTING
            System.out.println("\n\nTESTING: populateBackgroundsData()");
            int j = backgroundsData.size();
            for(int i = 0; i < j; i++){
                System.out.println("Index " + i + " = " + backgroundsData.get(i));
            System.out.println("\n\n");
            //close all stremas
            backgroundsFIS.close();
            backgroundsBIS.close();
            backgroundsDIS.close();
            } catch (FileNotFoundException e) {
                System.out.println("Error: File Not Found");
            } catch (IOException e) {
                System.out.println("Error: IO Exception Thrown");
        public void populateBackgroundsList(){
            backgroundsList = new ArrayList<JPanel>();
            int j = backgroundsData.size();
            System.out.println("number of backgrounds = " + j);
            backgroundsList = new ArrayList<JPanel>();
            for(int i = 0; i < j; i++){
                String tempBackgroundData = backgroundsData.get(i);
                JPanel backgroundJP = new JPanel(new GridLayout(1,2));
                JLabel backgroundNameJL = new JLabel();               
                JLabel backgroundIconJL = new JLabel();
                //split the string string and egt the background name and URL
                String[] splitBGData = tempBackgroundData.split(",");
                String backgroundName = splitBGData[0];
                String backgroundURL = splitBGData[1];
                String backgroundIcon = splitBGData[2];
                System.out.println("\nbackgroundName = " + backgroundName);
                System.out.println("\nbackgroundURL = " + backgroundURL);
                System.out.println("\nbackgroundIcon = " + backgroundIcon + "\n");
                backgroundNameJL.setText(backgroundName);
                backgroundIconJL.setIcon(new javax.swing.ImageIcon(backgroundIcon));
                backgroundJP.add(backgroundNameJL);
                backgroundJP.add(backgroundIconJL);
                backgroundJP.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
                //Name the JP as the background URL so it can be found
                //May be useful sicne the data file may need to contain 3 fields in future
                //this is incase the preview image (icon) is different from the acctual background
                //most liekly in the case of more complex ppictures rather then repeating patterns
                backgroundJP.setName(backgroundURL);
                //Add the JP to the Array List
                backgroundsList.add(backgroundJP);
            //TESTING
            System.out.println("\n\nTESTING: populateBackgroundsList()");
            j = backgroundsList.size();
            for(int i = 0; i < j; i++){
                System.out.println("Index " + i + " = " + backgroundsList.get(i));
            System.out.println("\n\n");
    }So thats my program so far, if theres anythign that needs clarifying then please jsut ask. Thank you very much for the help!

  • Help with struts tags

    how do i print this arraylist using tags in struts... i mean using iterate and bean write tags.
    <%
    java.util.ArrayList alist= new java.util.ArrayList();
    java.util.HashMap map = new java.util.HashMap();
    map.put("ID","1");
    map.put("GUID","101010101");
    map.put("STAT","01");
    java.util.HashMap map2 = new java.util.HashMap();
    map2.put("ID","2");
    map2.put("GUID","202020202");
    map2.put("STAT","02");
    java.util.HashMap map3 = new java.util.HashMap();
    map3.put("ID","3");
    map3.put("GUID","303030303");
    map3.put("STAT","03");
    alist.add(map);
    alist.add(map2);
    alist.add(map3);
    System.out.println("Arraylist:"+alist);
    session.setAttribute("array",alist);
    %>i need to print that alist in a tabular fashion..... like this
                ID                       GUID                      STATUS
                1                     1010101                          01
                2                     2020202                          02
                3                     3030303                          03how do i do that
    plz help
    praneeth

    how do i print this arraylist using tags in struts... i mean using iterate and bean write tags.
    <%
    java.util.ArrayList alist= new java.util.ArrayList();
    java.util.HashMap map = new java.util.HashMap();
    map.put("ID","1");
    map.put("GUID","101010101");
    map.put("STAT","01");
    java.util.HashMap map2 = new java.util.HashMap();
    map2.put("ID","2");
    map2.put("GUID","202020202");
    map2.put("STAT","02");
    java.util.HashMap map3 = new java.util.HashMap();
    map3.put("ID","3");
    map3.put("GUID","303030303");
    map3.put("STAT","03");
    alist.add(map);
    alist.add(map2);
    alist.add(map3);
    System.out.println("Arraylist:"+alist);
    session.setAttribute("array",alist);
    %>i need to print that alist in a tabular fashion..... like this
                ID                       GUID                      STATUS
                1                     1010101                          01
                2                     2020202                          02
                3                     3030303                          03how do i do that
    plz help
    praneeth

  • Hande Iterator on smart

    hi all ,
    I try the collection and the iterator , How can I modify my code then let my arraylist , linklist , and set share the same Iterator
    *public class Collection {*
    *public static void main(String[] args) {*
    *// create string Object*
    *String n[]={*
    new String("Boston"),
    new String(" New York")
    ArrayList al = new ArrayList();
    *// add elements to the array list*
    al.addAll(Arrays.asList(n));
    al.add(new Integer(1));
    System.out.print("The arrayList of al: ");
    *for (Iterator it = al.iterator(); it.hasNext(); ) {*
    Object element = it.next();
    System.out.println(element);
    *// Set up testing data*
    HashSet hs= new HashSet();
    *// add integer*
    hs.add(new Integer(100));
    hs.add(new Integer(200));
    hs.add(new Integer(300));
    List list = Arrays.asList(n);
    hs.add(list);
    Iterator itr = hs.iterator();
    System.out.println("HashSet contains : ");
    while(itr.hasNext())
    System.out.println(itr.next());
    LinkedList mylink=new LinkedList();
    *// add integer*
    mylink.add(new Integer(4));
    mylink.add(new Integer(5));
    mylink.add(new Integer(6));
    *// add string object*
    mylink.add("Hello");
    mylink.add("ya");
    System.out.println("LinkedList contains : ");
    itr = mylink.iterator();
    while(itr.hasNext())
    System.out.println(itr.next());
    *}*

    Hjava wrote:
    so , not way to improve it? That depends on your requirements.
    feel not good to have that much Iterator in one class!What are you talking about?

  • How to keep value in arrayList and print into matrix form.

    compute all primes less than N, and display the results
    step by step .summarize the computed results in an easy-to-read format.(matrix)
    The program starts by asking for an integer value N from the user. Print out the initial matrix
    of numbers from 2 to N.
    To find all primes less than N, begin by making a table of integers from 2 to N.
    Find the smallest integer i, that is NOT prime and NOT crossed out. Mark i as a prime
    number and cross out 2i, 3i, 4i, ?, ni N.
    At this point, program should print the intermediate results in a matrix format, and pause
    until any key is pressed before proceeding.clear screen every
    time prior to printing the intermediate results (in the matrix format).
    When i > N , the algorithm terminates. screen is cleared once again,
    before the program prints the final results in the matrix format.
    Following are the requirements for the matrix format:
    - The matrix consists of 10 columns
    - The number of rows varies, depending on the input N
    - Initial matrix: The program prints an empty string in place of 1
    - Intermediate matrix: The program prints values for all prime numbers and numbers
    that are not crossed out. The program prints an empty string for each crossed-out
    number.
    Final matrix: The program prints only the prime numbers less than N
    P.S I want to write at least 3 classes

    This is my new first class but it have an error
    import java.io.*;
    import java.util.*;
    public class ArrayListExample2 {
        public static void main(String[] args)throws IOException {
            ArrayListExample listExample = new ArrayListExample();
            listExample.doArrayListExample();
        public void doArrayListExample()throws IOException {
              BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
             System.out.print("enter limit : ");
              int max=Integer.parseInt(br.readLine());
              System.out.println();
            int counter = 2;
            List listA = new ArrayList();// int list
            //List listB = new ArrayList(); //string list
            for (int i = 2; i <= max; i++) {
                System.out.print("\t" + i );
                listA.add(new Integer(i)); //???????2-max ??listA
              int count =0;
              BufferedReader en = new BufferedReader(new InputStreamReader(System.in));
              while(count<Math.sqrt(max))
                     // max may be number of input or size of array list
              //BufferedReader en = new BufferedReader(new InputStreamReader(System.in));
              System.out.println ("Please enter");
              en.readLine();// wait for enter
              listA.removeNotPrime();
              count++;
         public void removeNotPrime()// what parametor?Need?
              for (int i=0;i<Math.sqrt(max)))
                   int prime = listA.get(i);
                        for (int j=i+1;i<=listA.size();j++)
                         int val = listA.get(j);
                        if (val%prime==0)
                        listA.remove(j);
    This part for test
            for (int i = 0; i <= max; i++)  // printttttttttt
                //System.out.print("\t" + i );
                   System.out.print("\t" + listA.get(i);
                // call class printMatrix;
    }

  • 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)

  • Help :add multiple rows from Resultset to ArrayList ?

    My query returns one column and multiple rows. In Java code , I am trying to get this data in array or arraylist through ResultSet
    ex:
    item_num
    p001
    p002
    p003
    when I print, it only gets the item in the first row.
    ArrayList myArrayList = new ArrayList();
    resultset = preparedstatement.executeQuery();
    if (resultset.next())
    myArrayList.add(new String(resultset.getString("item_num")));
    Print:
    for (int j = 0 ; j < myArrayList.size() ; j++ )
    System.out.println((String)myArrayList.get(j)); --this prints only the first item.
    can someone assist ?

    changing if to while fixed it.

  • 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

Maybe you are looking for

  • IPhoto Galleries not appearing in Aperture's Moblie Me.

    How do import iPhoto 08 web gallery albums into aperture 2? When I go to Preferences-> Moblie Me I don't see the galleries which have been published from iPhoto.

  • How do i make a pure actionscript as simple native window?

    Hello @all anythings, I ask about a sample pure framework by Flex for Adobe Air. An Example: Window with customizable buttons - If i use boolen  for visible or invisible buttons like this: http://livedocs.adobe.com/flex/3/html/help.html?content=Part6

  • Mouseover effects not uniform across the menu

    I created a simple menu in Dreamweaver CS4 using css. The two menu tabs with drop-down effects have a glitch in the top tier. The Black text on white background turns white on mouseover causing the button to go blank. Where would I go in the SpryMenu

  • Can someone explain icloud?

    Can someone please explain iCloud?  I understand that it syncs music, photos etc. over all devices, but what I don't understand is: 1) will I need an internet connection to listen to music that is on my computer?  2) If I don't sign up for the musicm

  • Please respond this this poll if you are developing Forms applications

    http://forums.oracle.com/forums/poll.jspa?pollID=231 We are looking at our platform support for 11g, can you post the OS platform you use for BUILDING (not running) Oracle Forms. Thanks Grant