Display data drom ArrayList String in Strunts

Hi everybody,
I'm very new to Struts. Can anyone tell me how to display data drom ArrayList<String> in Strunts in JSP page?

have you tried creating a data control? Right click on java class in application window and select 'create data control'
Then drag the new control from the data-control palette onto your page, selecting the type of UI component you want to create from the drop down list before you drag...
Matthew

Similar Messages

  • Displaying data contained in string ina excel sheet

    hi,
    I am provided two string arrays containing data fetchd from data base.
    I am required to display them in M-s EXcel format .
    I have to write a servlet , to accomplish tis task.
    Can any one suggest me a way to start
    i used the following sample tostart with:
         String a=new String("arvind");
              response.setContentType("application/ms-excel");
              java.io.PrintWriter out1= response.getWriter();
              out1.write(a);
    but upon clicking the button to generate it says, unable to create xxxxx.jsp page do u want to open a new file
    how do i overcome this problem

    If you had made a search, you would have found hints about Apache POI.
    http://jakarta.apache.org/poi/index.html

  • Display data string as text list

    Hi all,
    How to display data line by line? refer to attachment jpg
    thanks,
    simon
    Attachments:
    help.JPG ‏63 KB

    Hi simon76,
    here is one solution for it. Another way is to create all vis first, and change only the visible state.
    Mike
    Attachments:
    Config_LV80.vi ‏28 KB
    Start_LV80.vi ‏15 KB

  • How to display an output in string data type in an applet

    hello there..may i know how to display an output of string type in an applet

    thanks.i'll try

  • Walkthrough: Displaying Data from Oracle database in a Windows application.

    This article is intended to illustrate one of the most common business scenarios such as displaying data from Oracle database on a form in a Windows application using DataSet objects and .NET Framework Data Provider for Oracle.
    You can read more at http://www.c-sharpcorner.com/UploadFile/john_charles/WalkthroughDisplayingDataOracleWindowsapplication05242007142059PM/WalkthroughDisplayingDataOracleWindowsapplication.aspx
    Enjoy my article.

    hi,
    this is the code :
    public class TableBean {
    Connection con ;
    Statement ps;
    ResultSet rs;
    private List perInfoAll = new ArrayList();
    public List getperInfoAll() {
    int i = 0;
    try
    con = DriverManager.getConnection("url","root","root");
    ps = con.createStatement();
    rs = ps.executeQuery("select * from user");
    while(rs.next()){
    System.out.println(rs.getString(1));
    perInfoAll.add(i,new perInfo(rs.getString(1),rs.getString(2),rs.getString(3)));
    i++;
    catch (Exception e)
    System.out.println("Error Data : " + e.getMessage());
    return perInfoAll;
    public class perInfo {
    String uname;
    String firstName;
    String lastName;
    public perInfo(String firstName,String lastName,String uname) {
    this.uname = uname;
    this.firstName = firstName;
    this.lastName = lastName;
    public String getUname() {
    return uname;
    public String getFirstName() {
    return firstName;
    public String getLastName() {
    return lastName;
    ADF table code:
    <af:table value="#{tableBean.perInfoAll}" var="row"
    binding="#{backing_Display.table1}" id="table1">
    <af:column sortable="false" headerText=""
    align="start">
    <af:outputText value="#{row.firstName"/>//---> Jdeveloper 11g doesn't allow me to use this.. it says firstName is an unknown property..
    </af:column>
    </af:table>
    Please tell me is this the way to do it.. or is it a must to use the DataCollection from the data controls panel...
    Thanks...

  • HELP! retrieving and displaying data with JavaBean but Page is Blank!!

    Please help. I am trying to display data for user by appending the userid as parameter in the URL but I get a blank page and nothing displays in my jsp page.
    //info.java
    package database;
    public class Info{
    private String user;
    public Info(){
    public void setuser(String user)
        this.user = user;
      public String getuser()
        return user;
       public Collection getInfo() throws NamingException, SQLException {
                    ArrayList list = new ArrayList();
                    InitialContext initCtx = new InitialContext();
                    //OTHER CONNECTION STATEMENTS
    String sql = "SELECT ADDR FROM TABLENAME WHERE user=' ?'";
                    try {
                            conn = ds.getConnection();
    pstmt = conn.prepareStatement(sql);
    pstmt.setString(1, this.user);
    rs = pstmt.executeQuery();
    while(rs.next()) {
            InfoBean tsel = new InfoBean(rs.getString("addr"), this.user);
    list.add(tsel);
          //catch SQLexception
    } finally {
    try{
               if (initCtx != null)  initCtx.close();
            if (rs != null)  rs.close();
            if (pstmt != null) pstmt.close();
            if (conn != null) conn.close();
    //catch SQLException statment
          return list;
    //InfoBean.java
    package database;
    public class infoBean
    private String user;
    private String addr;
    public infoBean(){
    public infoBean(String addr, String user)
    this.user = user;
    this.addr = addr;
    public String getaddr()
    return addr;
    public String getuser(){
    return user;
    public void setaddr(String addr){
    this.addr = addr;
    public void setuser(String user){
    this.user = user;
    //index.jsp
    <jsp:useBean id="row" class="database.Info" scope="request">
    <jsp:setProperty name="row" property="user" param="user"/>
    </jsp:useBean>
    <c:if test=${!empty param.user}">
    <c:forEach items="${row.info}" var="t1">
    <td>${t1.addr}</td<>
    </c:forEach>
    </c:if>

    OK, before we all go rummaging through your code--does your SQL statement return values when you execute it as a stand alone adhoc query?

  • Display data in JTable

    I am trying to display data from database into the JTable swing component. I can see the table and the heading coming from the vector. I cannot see why the data from the databse table is not loaded on to the Jtable. I just get a table with 6 rows blank.
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    import java.io.*;
    import java.sql.*;
    import java.util.*;
    public class dataTable extends JApplet
    String dbdriver="jdbc:oracle:thin:@ds1.ctateu.edu:1521:wpac";
    String dbuser="system";
    String dbpass="pass";
    Container c;
    JScrollPane jsp;
    JTable table;
    int v,h;
    Connection connection;
    Statement stmt;
    ResultSet rs;
    String param_start,param_end, param_disp_start, param_disp_end,param_shortdesc, param_longdesc;
    public void init()
    c= getContentPane();
    c.setLayout (new BorderLayout());
    v=ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS;
    h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS;
    Vector heading = new Vector();
    heading.addElement("Event Start Date");
    heading.addElement("Event End Date");
    heading.addElement("Display Start Date");
    heading.addElement("Display End Date");
    heading.addElement("Short Description");
    heading.addElement("Long Description");
    Vector data = new Vector();
    try
    Class.forName("oracle.jdbc.driver.OracleDriver");
    connection=DriverManager.getConnection(dbdriver,dbuser,dbpass);
    stmt=connection.createStatement();
    rs= stmt.executeQuery("select * from univevents");
    while(rs.next())
    param_start = rs.getString("start_date");
    param_end = rs.getString("end_date");
    param_disp_start = rs.getString("display_start");
    param_disp_end =rs.getString("display_end");
    param_shortdesc = rs.getString("short_desc");
    param_longdesc = rs.getString("long_desc");
    catch (Exception e)
    //JOptionPane.showMessageDialogue("Exception: "+e.getMessage());
    data.addElement(param_start);
    data.addElement(param_end);
    data.addElement(param_disp_start);
    data.addElement(param_disp_end);
    data.addElement(param_shortdesc);
    data.addElement(param_longdesc);
    table = new JTable(data, heading);
    jsp = new JScrollPane(table,v,h);
    //Add scrollpane to container
    c.add("Center",jsp);
    }//init
    }//JApplet

    Your data vector should be a Vector of Vectors.
    I think you need to change your loop to look something like this:
    while(rs.next())
        Vector row = new Vector();
        row.addElement( rs.getString("start_date") );
        row.addElement( rs.getString("end_date") );
        row.addElement( rs.getString("display_start") );
        row.addElement( rs.getString("display_end") );
        row.addElement( rs.getString("short_desc") );
        row.addElement( rs.getString("long_desc") );
        data.addElement( row );
    } Then remove your data.addElement() statements found outside the loop.

  • Retrieving datas with ArrayList

    Below, im trying to get 6 columned records from the access database.
    //PNL 1:
                                  PNL1=new JPanel();
                                  PNL1.setLayout(new BorderLayout(15,15));
                                                    java.awt.List veri;
                                                    ArrayList veri2;
                                  lblABaslik=new JLabel("Arama Sonuclari :");
                                  String[] sutunAdlari={"Tarih","Arac","Kategori","Aciklama","Detay","Miktar"};
                                  int sayac=-1;
                                  java.util.Date tarih;int arac;int kategori;int aciklama;String detay;int tutar;
                                       try {
                                            String url="jdbc:odbc:Driver={MicroSoft Access Driver (*.mdb)};DBQ=..\\bekir.mdb";
                                            String query="select * from harcamalar where tarih between # 2003-11-14 # and #2003-12-14 #";
                                            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                                            Connection con=DriverManager.getConnection(url,"serdar","serdar");
                                            Statement stmt=con.createStatement();
                                            ResultSet rs = stmt.executeQuery(query);
                                                                     veri=new java.awt.List(6);
                                                                     veri2=new ArrayList();
                                                                     String ekle;
                                                                     while(rs.next()) {
                                                                       ekle=new String(rs.getString("tarih"));
                                                                           veri.add(ekle);
                                                                       ekle=new String(rs.getString("arac_id"));
                                                                           veri.add(ekle);
                                                                       ekle=new String(rs.getString("kategori_id"));
                                                                           veri.add(ekle);
                                                                       ekle=new String(rs.getString("aciklama_id"));
                                                                           veri.add(ekle);
                                                                       ekle=new String(rs.getString("detay"));
                                                                           veri.add(ekle);
                                                                       ekle=new String(rs.getString("miktar"));
                                                                           veri.add(ekle);
                                                                     veri2.add(veri);
                                            rs.close();
                                            stmt.close();
                                            con.close();
                                       catch (ClassNotFoundException e2){
                                            e2.printStackTrace(System.err);
                                       catch (SQLException e2){
                                       System.err.println("SQL state: " + e2.getSQLState());
                                       System.err.println("SQL error: " + e2.getErrorCode());
                                       e2.printStackTrace(System.err);
                                                    table=new JTable(veri2,sutunAdlari);
                                  table.setPreferredScrollableViewportSize(new Dimension(600,100));
                                  JScrollPane scrollpane=new JScrollPane(table);
                                  PNL1.add("North",lblABaslik);
                                  PNL1.add("Center",scrollpane);
                                  table.addMouseListener(new MouseAdapter() {
                                       public void mouseClicked(MouseEvent e) {
                                            System.out.println(table.getSelectedRow());
    but i get the error :
    "BekirAna2.java": cannot resolve symbol: constructor JTable (java.util.ArrayList,java.lang.String[])in class javax.swing.JTable at line 1928, column 55
    which represents the line :
    table=new JTable(veri2,sutunAdlari);
    thanx

    i changed the codes with Vector definitions;
                             //PNL1 :
                                  PNL1=new JPanel();
                                  PNL1.setLayout(new BorderLayout(15,15));
                                                     Vector veri;
                                                     Vector veri2;
                                                     //ArrayList veri2;
                                  lblABaslik=new JLabel("Arama Sonuclari :");
                                  //Object[][] veri=new Object[10][7];
                                  //veri[0][0] = new String("foo"); //etc.
                                  String[] sutunAdlari={"Tarih","Arac","Kategori","Aciklama","Detay","Miktar"};
                                  int sayac=-1;
                                  java.util.Date tarih;int arac;int kategori;int aciklama;String detay;int tutar;
                                       try {
                                            String url="jdbc:odbc:Driver={MicroSoft Access Driver (*.mdb)};DBQ=..\\bekir.mdb";
                                            //String query="select * from harcamalar";
                                            String query="select * from harcamalar where tarih between # 2003-11-14 # and #2003-12-14 #";
                                            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                                            Connection con=DriverManager.getConnection(url,"serdar","serdar");
                                            Statement stmt=con.createStatement();
                                            ResultSet rs = stmt.executeQuery(query);
                                                                     veri=new Vector();
                                                                     //veri2=new ArrayList();
                                                                     veri2 = new Vector();
                                                                     String ekle;
                                                                     while(rs.next()) {
                                                                       ekle=new String(rs.getString("tarih"));
                                                                           veri.add(ekle);
                                                                       ekle=new String(rs.getString("arac_id"));
                                                                           veri.add(ekle);
                                                                       ekle=new String(rs.getString("kategori_id"));
                                                                           veri.add(ekle);
                                                                       ekle=new String(rs.getString("aciklama_id"));
                                                                           veri.add(ekle);
                                                                       ekle=new String(rs.getString("detay"));
                                                                           veri.add(ekle);
                                                                       ekle=new String(rs.getString("miktar"));
                                                                           veri.add(ekle);
                                                                     veri2.add(veri);
                                            rs.close();
                                            stmt.close();
                                            con.close();
                                       catch (ClassNotFoundException e2){
                                            e2.printStackTrace(System.err);
                                       catch (SQLException e2){
                                       System.err.println("SQL state: " + e2.getSQLState());
                                       System.err.println("SQL error: " + e2.getErrorCode());
                                       e2.printStackTrace(System.err);
                                  //table=new JTable(veri,sutunAdlari);
                                                    table=new JTable(veri2,sutunAdlari);
                                  table.setPreferredScrollableViewportSize(new Dimension(600,100));
                                  JScrollPane scrollpane=new JScrollPane(table);
                                  PNL1.add("North",lblABaslik);
                                  PNL1.add("Center",scrollpane);
                                  table.addMouseListener(new MouseAdapter() {
                                       public void mouseClicked(MouseEvent e) {
                                            System.out.println(table.getSelectedRow());
                                  });but i still get the error alike:
    "BekirAna2.java": cannot resolve symbol: constructor JTable (java.util.Vector,java.lang.String[])in class javax.swing.JTable at line 1931, column 55
    pointing the line;
    table=new JTable(veri2,sutunAdlari);

  • Display data in excel

    Hi, I have program which display data in Excel layout of ALV loaded from internal table..
    It means that in sap i received excel sheet with all its functionality.
    The problem is that sometimes there are missed some rows with data.
    Did someone meet with similar situation?
    Regards,
    Joanna

    HI
    DATA: v_file LIKE rlgrap-filename,
            v_filename TYPE string.
      REFRESH i_matcontrol.
      CLEAR   i_matcontrol.
      TRANSLATE v_exten TO UPPER CASE.
      IF v_exten = 'XLS'.
        v_file = p_p_file.
        CALL FUNCTION 'TEXT_CONVERT_XLS_TO_SAP'
          EXPORTING
            i_field_seperator    = 'X'
            i_tab_raw_data       = ws_rawdata
            i_filename           = v_file
          TABLES
            i_tab_converted_data = i_data.
      ELSEIF v_exten = 'TXT'.
        v_filename = p_p_file.
    File upload
        CALL FUNCTION 'GUI_UPLOAD'
          EXPORTING
            filename                = v_filename
            filetype                = 'ASC'
            has_field_separator     = 'T'
          TABLES
            data_tab                = i_data
          EXCEPTIONS
            file_open_error         = 1
            file_read_error         = 2
            no_batch                = 3
            gui_refuse_filetransfer = 4
            invalid_type            = 5
            no_authority            = 6
            unknown_error           = 7
            bad_data_format         = 8
            header_not_allowed      = 9
            separator_not_allowed   = 10
            header_too_long         = 11
            unknown_dp_error        = 12
            access_denied           = 13
            dp_out_of_memory        = 14
            disk_full               = 15
            dp_timeout              = 16
            OTHERS                  = 17.
        CASE sy-subrc.
          WHEN 1.
            MESSAGE e001(00) WITH text-001.
            STOP.
          WHEN 2.
            MESSAGE e001(00) WITH text-002.
            STOP.
          WHEN 0.
            IF i_data IS INITIAL.
              MESSAGE s001(00) WITH text-008.
            ENDIF.
        ENDCASE.
      ENDIF.
      DELETE i_data WHERE matnr IS INITIAL AND
                                  werks IS INITIAL.

  • Display data from entity into a Jtextareaþ

    Hello everyone,
    How do I display data I am retrieving from the entity into a Jtextarea?
    Here is how I am doing it:
    in the main class of the application client, I set up a method
    which stores the remote interface so I can call the method
    anyway of my application.
    public class Main extends javax.swing.JFrame {
         @EJB
                private static  BRemote bRemote;
           //accessor method
           static BRemote getBRemote() {
                  return bRemote;
          // I can out the method to request data
          public void findB(String bal){
            Main.getBRemote().findbyDname(bal);
            searesttxta.setText(getBRemote().toString());
    } The searesttxta is the JTextArea.
    the data I get is
    folder._BRemote_Wrapper@3ce08241
    So, how do I get to display the entity in the textarea?
    thanks
    eve

    Hi,
    Thank you for your reply.
    Yes I do have sets and get methods but I also understand I can
    use the to string too. But to attach it to the JTextArea.
    eve

  • Display data in diagonally in table using XML publisher

    Hi,
    I need to display data of the invoice which contains columns ( invoice_number,receipt_number,amount,quantity)
    where i need to dispay amount and quantity diagonally for the invoces i.e. the data will extend dynamically.
    please give me an idea to resolve this issue.
    Thanks in advance

    in wdinit(),
    Collection col = new ArrayList();
    try{                    
      MyCommandBean bean = new MyCommandBean();
      col = bean.getDataFromDbViaEJB();
      wdContext.nodeMyCommandBean().bind(col);
    } catch (Exception ex) {
       ex.printStackTrace(ex); 
    in your JavaBean model class, MyCommandBean getDatafromDbViaEJB() method:
    Collection col = new ArrayList();
    Collection newcol = new ArrayList();
    //include your own context initialization etc...
    col = local.getDataViaSessionBean(param);
    // if your returned result also a bean class, reassigned it to current MyCommandBean
    for (Iterator iterator = col.iterator(); iterator.hasNext();) {
        MyOtherBean otherBean=(MyOtherBean)iterator.next();
        MyCommmandBean bean = new MyCommandBean();
        bean.attribute1 = outBean.getAttirbute1();
        // get other attibutes
        newcol.add(bean);
    return newcol;

  • How can I display date+time and not the point number in excell?

    Hi everyone,
    Could anybody tell me how I can save date + time to a file, so that  I can display on a diagram(excel) : date+time in (ox) and data (oy)? :
    My program sets in (ox) the point number and not the date+time....( although  date and time are written correctly in the column...)
    Any help would be great,
    Thanks,
    regards,
    Marc

    hi there,
    excel uses 01.01.1900 00:00 as the time offset, LabVIEW uses 01.01.1904 02:00, so you can't display the correct datetime in excel when you write the time as a fractional number of seconds from LabVIEW. you must format the datetime in LabVIEW to a string and write that to the column. use the "Format Date/Time String" - function and for example "%d.%m.%Y %H:%M:%S%3u" as the format string (see the functions help for more examples). you also could format your data to a string using "Format Into String" - function and write the file as a 2D string array. the decimal point you have to use depends on your system and its settings, but you can specify the decimal point in the Format string like "%.;%f" (means fractional number with point as decimal point).
    best regards
    chris 
    Best regards
    chris
    CL(A)Dly bending G-Force with LabVIEW
    famous last words: "oh my god, it is full of stars!"

  • Reading & writing to file using ArrayList String incorrectly

    Hi Java Experts,
    I am running out of ideas on why my findSnomedCodes.java program is filling up the output file (Snomed-Codes.txt) with the
    same information ([M44110|T33010, , M92603|T10350, ]) continuously. This program goes through a dummy patient result file
    and pickup the 3rd line of each record and insert it into an ArrayList of String before writing it into a Snomed-Codes.txt
    file. A followed up method prints out everything from Snomed-Codes.txt.
    Below is the source code of findSnomedCodes.java program:
    import java.io.*;
    import java.io.IOException;
    import java.lang.String;
    import java.lang.Character;
    import java.util.regex.*;
    import java.util.ArrayList;
    import java.util.List;
    public class FindSnomedCode {
    static List<String> complete_records = new ArrayList<String>();
    static public void getContents(File existingFile) {
    StringBuffer contents = new StringBuffer();
    BufferedReader input = null;
    int line_number = 0;
    int number_of_records = 0;
    String snomedCodes = null;
    try {
    input = new BufferedReader( new FileReader(existingFile) );
    String current_line = null;
    while (( current_line = input.readLine()) != null) {
    // Create a pattern to match for the "\"
    Pattern p = Pattern.compile("\\\\");
    // Create a matcher with an input string
    Matcher m = p.matcher(current_line);
    boolean beginning_of_record = m.find();
    if (beginning_of_record) {
    line_number = 0;
    number_of_records++;
    } else {
    line_number++;
    if (line_number == 2) {
    snomedCodes = current_line;
    System.out.println(snomedCodes);
    complete_records.add(current_line);
    catch (FileNotFoundException ex) {
    ex.printStackTrace();
    catch (IOException ex){
    ex.printStackTrace();
    finally {
    try {
    if (input!= null) {
    input.close();
    catch (IOException ex) {
    ex.printStackTrace();
    static public void setContents(File reformatFile, List snomedCodes)
    throws FileNotFoundException, IOException {
    Writer output = null;
    try {
    output = new BufferedWriter( new FileWriter(reformatFile) );
    while (snomedCodes.iterator().hasNext())
    output.write( snomedCodes.toString() );
    finally {
    if (output != null) output.close();
    static public void printContents(File existingFile) {
    //...checks on existingFile are elided
    StringBuffer contents = new StringBuffer();
    BufferedReader input = null;
    int line_number = 0;
    int number_of_records = 0;
    long total_number_of_lines = 0;
    String snomedCodes = null;
    try {
    input = new BufferedReader( new FileReader(existingFile) );
    String current_line = null;
    while (( current_line = input.readLine()) != null)
    System.out.println(current_line);
    catch (FileNotFoundException ex) {
    ex.printStackTrace();
    catch (IOException ex){
    ex.printStackTrace();
    finally {
    try {
    if (input!= null) {
    input.close();
    catch (IOException ex) {
    ex.printStackTrace();
    public static void main (String args[]) throws IOException {
    File currentFile = new File("D:\\AP Data Conversion\\1988\\dummy_test_records.txt");
    getContents(currentFile);
    File snomedFile = new File( "D:\\AP Data Conversion\\1988\\Snomed-Codes.txt");
    setContents(snomedFile, complete_records);
    printContents(snomedFile);
    The output from Netbeans/Java is as follows:
    M44110|T33010
    M92603|T10350
    Exception in thread "main" java.io.IOException: There is not enough space on the disk
    at java.io.FileOutputStream.writeBytes(Native Method)
    at java.io.FileOutputStream.write(FileOutputStream.java:260)
    at sun.nio.cs.StreamEncoder$CharsetSE.writeBytes(StreamEncoder.java:336)
    at sun.nio.cs.StreamEncoder$CharsetSE.implClose(StreamEncoder.java:427)
    at sun.nio.cs.StreamEncoder.close(StreamEncoder.java:160)
    at java.io.OutputStreamWriter.close(OutputStreamWriter.java:222)
    at java.io.BufferedWriter.close(BufferedWriter.java:250)
    at FindSnomedCode.setContents(FindSnomedCode.java:90)
    at
    FindSnomedCode.main(FindSnomedCode.java:134)---------------------------------------------------------------------------------
    The content of Snomed-Codes.txt file is filled with continuous lines of [M44110|T33010, , M92603|T10350, ] as follows:
    [M44110|T33010, , M92603|T10350, ][M44110|T33010, , M92603|T10350, ][M44110|T33010, , M92603|T10350, ][M44110|T33010, ,
    M92603|T10350, ][M44110|T33010, , M92603|T10350, ][M44110|T33010, , M92603|T10350, ][M44110|T33010, , M92603|T10350,
    ][M44110|T33010, , M92603|T10350, ][M44110|T33010, , M92603|T10350, ][M44110|T33010, , M92603|T10350, ][M44110|T33010, ,
    M92603|T10350, ][M44110|T33010, , M92603|T10350, ][M44110|T33010, , M92603|T10350, ][M44110|T33010, , M92603|T10350,
    I must have done something wrong with the ArrayList.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    while (snomedCodes.iterator().hasNext())
      output.write( snomedCodes.toString() );
    }Here you have some kind of a list or something (I couldn't stand to read all that unformatted code but I suppose you can find out). It has an iterator which gives you the entries of the list one at a time. You keep asking if it has more entries -- which it does -- but you never get those entries by calling the next() method, so it always has all the entries still available.
    And your code inside the loop is independent of the iterator, so it's rather pointless to iterate over the entries and output exactly the same data for each entry. Even if you were iterating correctly.

  • Reading & writing to file using ArrayList String incorrectly (2)

    I have been able to store two strings (M44110|T33010, M92603|T10350) using ArrayList<String>, which represent the result of some patient tests. Nevertheless, the order of these results have been stored correctly.
    E.g. currently stored in file Snomed-Codes as -
    [M44110|T33010, M92603|T10350][M44110|T33010, M92603|T10350]
    Should be stored and printed out as -
    M44110|T33010
    M92603|T10350
    Below is the detail of the source code of this program:
    import java.io.*;
    import java.io.IOException;
    import java.lang.String;
    import java.util.regex.*;
    import java.util.ArrayList;
    public class FindSnomedCode {
        static ArrayList<String> allRecords = new ArrayList<String>();
        static public ArrayList<String> getContents(File existingFile) {
            StringBuffer contents = new StringBuffer();
            BufferedReader input = null;
            int line_number = 0;
            int number_of_records = 0;
            String snomedCodes = null;
            ArrayList<String> complete_records = new ArrayList<String>();
            try {
                input = new BufferedReader( new FileReader(existingFile) );
                String current_line = null;
                while (( current_line = input.readLine()) != null) {
                    // Create a pattern to match for the "\"
                    Pattern p = Pattern.compile("\\\\");
                    // Create a matcher with an input string
                    Matcher m = p.matcher(current_line);
                    boolean beginning_of_record = m.find();
                    if (beginning_of_record) {
                        line_number = 0;
                        number_of_records++;
                    } else {
                        line_number++;
                    if ( (line_number == 2) && (current_line.length() != 0) ) {
                        snomedCodes = current_line;
                        System.out.println(snomedCodes);
                        complete_records.add(current_line);
            catch (FileNotFoundException ex) {
                ex.printStackTrace();
            catch (IOException ex){
                ex.printStackTrace();
            finally {
                try {
                    if (input!= null) {
                        input.close();
                catch (IOException ex) {
                    ex.printStackTrace();
            return complete_records;
        static public void setContents(File reformatFile, ArrayList<String> snomedCodes)
                                     throws FileNotFoundException, IOException {
           Writer output = null;
            try {
                output = new BufferedWriter( new FileWriter(reformatFile) );
                  for (String index : snomedCodes) {
                      output.write( snomedCodes.toString() );
            finally {
                if (output != null) output.close();
        static public void printContents(File existingFile) {
            StringBuffer contents = new StringBuffer();
            BufferedReader input = null;
            int line_number = 0;
            int number_of_records = 0;
            String snomedCodes = null;
            try {
                input = new BufferedReader( new FileReader(existingFile) );
                String current_line = null;
                while (( current_line = input.readLine()) != null)
                    System.out.println(current_line);
            catch (FileNotFoundException ex) {
                ex.printStackTrace();
            catch (IOException ex){
                ex.printStackTrace();
            finally {
                try {
                    if (input!= null) {
                        input.close();
                catch (IOException ex) {
                    ex.printStackTrace();
        public static void main (String args[]) throws IOException {
            File currentFile = new File("D:\\dummy_patient.txt");
            allRecords = getContents(currentFile);
            File snomedFile = new File( "D:\\Snomed-Codes.txt");
            setContents(snomedFile, allRecords);
            printContents(snomedFile);
    }There are 4 patient records in the dummy_patient.txt file but only the 1st (M44110|T33010) & 3rd (M92603|T10350) records have results in them. The 2nd & 4th records have blank results.
    Lastly, could someone explain to me the difference between java.util.List & java.util.ArrayList?
    I am running Netbeans 5.0, jdk1.5.0_09 on Windows XP, SP2.
    Many thanks,
    Netbeans Fan.

    while (snomedCodes.iterator().hasNext())
      output.write( snomedCodes.toString() );
    }Here you have some kind of a list or something (I couldn't stand to read all that unformatted code but I suppose you can find out). It has an iterator which gives you the entries of the list one at a time. You keep asking if it has more entries -- which it does -- but you never get those entries by calling the next() method, so it always has all the entries still available.
    And your code inside the loop is independent of the iterator, so it's rather pointless to iterate over the entries and output exactly the same data for each entry. Even if you were iterating correctly.

  • Using JTables to display data from a text file

    How do I display data from a .txt file into a column inside a JTable?

    dont quite get the "vectors" part..
    by the way, my program is as follows
    * Damn Java ..
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    public class ScoreBoard extends JPanel {
    private boolean DEBUG = false;
    public ScoreBoard() {
    super(new GridLayout(1,0));
    String[] columnNames = {"Player's Name",
    "Time Completed",
    "$ Amount Earned $"};
    /* Object[][] data = {
    {"1",
    new Integer(5), new Integer(500)},
    {"2",
    new Integer(5), new Integer(3200)},
    {"3",
    new Integer(5), new Integer(1000)},
    {"4",
    new Integer(5), new Integer(100)},
    {"5",
    new Integer(5), new Integer(200)},
    final JTable table = new JTable(data, columnNames);
    table.setPreferredScrollableViewportSize(new Dimension(600, 90));
    if (DEBUG) {
    table.addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
    printDebugData(table);
    //Create the scroll pane and add the table to it.
    JScrollPane scrollPane = new JScrollPane(table);
    //Add the scroll pane to this panel.
    add(scrollPane);
    private void printDebugData(JTable table) {
    int numRows = table.getRowCount();
    int numCols = table.getColumnCount();
    javax.swing.table.TableModel model = table.getModel();
    System.out.println("Value of data: ");
    for (int i=0; i < numRows; i++) {
    System.out.print(" row " + i + ":");
    for (int j=0; j < numCols; j++) {
    System.out.print(" " + model.getValueAt(i, j));
    System.out.println();
    System.out.println("--------------------------");
    * Create the GUI and show it. For thread safety,
    * this method should be invoked from the
    * event-dispatching thread.
    private static void createAndShowGUI() {
    //Make sure we have nice window decorations.
    JFrame.setDefaultLookAndFeelDecorated(true);
    //Create and set up the window.
    JFrame frame = new JFrame("ScoreBoard");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Create and set up the content pane.
    ScoreBoard newContentPane = new ScoreBoard();
    newContentPane.setOpaque(true); //content panes must be opaque
    frame.setContentPane(newContentPane);
    //Display the window.
    frame.pack();
    frame.setVisible(true);
    public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();
    and i want to display the player name from a textfile.txt to the player column instead of hardcoding it like above. Thanks!

Maybe you are looking for