Comment on this code please

I would like your comments on this code. Doesn't it have a few oppertunities? I know it's jsp, but question is not directed toward the jsp, just the logic/syntax/etc. How about the == for starters?
<%
          String z_Desc = (((String)hshipTrackSummaryDocList.get("Z_DESC")) == null) ? "" : (String)hshipTrackSummaryDocList.get("Z_DESC");
          if (z_Desc  == "" ) {
     %>
     <%
          }else {
     %>
                  <%=(((String)hshipTrackSummaryDocList.get("Z_DESC")) == null) ? "" : (String)hshipTrackSummaryDocList.get("Z_DESC")%></font>
     <%
     %>

Hi mlovern! This code has several opportunities for "improvement". I noticed that the get("Z_DESC") method is called on hshipTrackSummaryDocList object several times. Each time, it returns the very same value. Hence, in the interests of efficiency, it's a better idea to call it once, save the return value and then use the latter.
Also, I'm not too clear about exactly what you intended to do in the else clause. As it stands, your else clause will cause the JSP to fail.
Be very careful while using the "==" operator while comparing strings. That causes object comparison, not object content comparison. The latter is the required test most of the time. Also, while comparing the contents of the strings, it's better to call the equals() method on the empty string or a constant string. So, if I needed to compare a test value against an empty string or a constant, here's how.
if ( "".equals( testString ) )
   // do something
else if ( SOME_CONSTANT.equals( testString ) )
   // do something
}In the above code, even if testString was null, a runtime exception will not be generated. However, if the equals() method was called on testString and it happened to be null, you'd be looking at an exception.
Here's how I would have written the code you supplied.
String zDescValue = (String) hshipTrackSummaryDocList.get( "Z_DESC" );
if ( zDescValue == null ) zDescValue = "";
if ( "".equals( zDescValue ) )
   // do something useful
else
  // do something else
}I've also come across similar situations. In order not to repeat the same code everywhere, I've wound up writing a couple of utility methods to assign "" to a string if it's null. Here are those methods.
public static String processStringValue( String inputString, String defaultValue )
   return ( inputString == null ? defaultValue : inputString );
public static String processStringValue( String inputString )
   return processStringValue( inputString, "" );
}Finally, you may want to be careful about the code fragments you post. From your post and profile, I can guess where you work. Your employer may or may not care if parts of their code start showing up on the Internet. It's better to create a general piece of code that approximates what you want to convey. However, it's better to be safe than sorry.
Hope this helps!
Cheers!

Similar Messages

  • Help me with this code please

    Hello,
    This is the first program that I have attempted to write alone....and I am stuck. I am trying to acquire data from a scope. I want the vi to only load the scope setup the first time the code is executed. Once the setup has been loaded I just want the vi to reinitialize the scope in order to acquire more data. I have tried first call, case structures, ...everything I can think of, but when I continuously run the vi, it still loops and reloads the setup each time. I have attached a picture of the vi code and outlined the area of code in question. The outlined case structure is programmed to initialize the scope to open communications, then clear any existing data, then recall a specific scope setup on true. On false, I only want this setting of code to initialize communications with the scope again without recalling the setup. Can a professional please explain how I am supposed to accomplish this. Thank you
    Solved!
    Go to Solution.
    Attachments:
    Code.jpg ‏69 KB

    If you use CONTINUOUSLY RUN to keep something running, you are in effect pushing the RUN button every time it stops, so the FIRST RUN function will return TRUE every time.
    There are ways to do exactly what you ask, but you're better off looking at the heart of your issue:
    You need a loop.
    Put a WHILE loop around the part you want to do repeatedly.
    Create a STOP button to stop the loop.
    Do your once-only INIT stuff outside the loop, and make sure the INIT part passes something into the WHILE loop 
    (to make sure the loop doesn't start until after INIT).
    Steve Bird
    Culverson Software - Elegant software that is a pleasure to use.
    Culverson.com
    Blog for (mostly LabVIEW) programmers: Tips And Tricks

  • Assistance needed on this code, please

    The code below is an example program:
    /* package demo.swing; */
    import javax.swing.JFrame;
    * Hello World application
    * @author MAbernethy
    public class HelloWorld extends JFrame
         private javax.swing.JLabel jLabel = null;
         private javax.swing.JTextField jTextField = null;
         private javax.swing.JButton jButton = null;
         public static void main(String[] args)
              HelloWorld w = new HelloWorld();
              w.setVisible(true);
         public HelloWorld()
              super();
              this.setSize(300, 200);
              this.getContentPane().setLayout(null);
              this.add(getJLabel(), null);
              this.add(getJTextField(), null);
              this.add(getJButton(), null);
              this.setTitle("Hello World");
         private javax.swing.JLabel getJLabel() {
              if(jLabel == null) {
                   jLabel = new javax.swing.JLabel();
                   jLabel.setBounds(34, 49, 53, 18);
                   jLabel.setText("Name:");
              return jLabel;
         private javax.swing.JTextField getJTextField() {
              if(jTextField == null) {
                   jTextField = new javax.swing.JTextField();
                   jTextField.setBounds(96, 49, 160, 20);
              return jTextField;
         private javax.swing.JButton getJButton() {
              if(jButton == null) {
                   jButton = new javax.swing.JButton();
                   jButton.setBounds(103, 110, 71, 27);
                   jButton.setText("OK");
              return jButton;
    The code compiles without any probems,but when run the following error messsages appear:
    Exception in thread "main" java.lang.Error: Donot use HelloWorld.add() use HelloWorld.getContentPane().add() instead
    at javax.swing.Jframe.creatRootPaneException(Jframe.java:465)
    at javax.swing.Jframe.addImpl(Jframe.java:491)
    at java.awt.Container.add(Container.java:518)
    at HelloWorld.<init>(HelloWorld.java:26)
    at HelloWorld.main(HelloWorld.java:17)

    Donot use HelloWorld.add() use
    HelloWorld.getContentPane().add() instead
    Isn't that obvious enough?D'oh! That was pretty obvious... ;)Yup, but my comment was directed at the OP, and I wish he reads your answer and remembers it next time. :)

  • Any comments about this code regaarding naming conventions and flow and e

    CREATE OR REPLACE PACKAGE SEODS02.ODS_APPEND_REPLACE
    AS
    /* Description : This procedure will start the process step for moving
    data from staging to live table for Append and Replace paradigms
    /**************** Change History ***********************************/
    /* Date Version Author Description */
    -- Global Specifications.
    package_name_in VARCHAR2(50) :='ODS_APPEND_REPLACE';
    v_location INTEGER := 10;
    v_cntl_schema VARCHAR2(20):= 'SCNTL02';
    -- Procedure Specifications.
    PROCEDURE APPEND_REPLACE_INSERT (job_name_in IN VARCHAR2,
    schema_name_in IN VARCHAR2,
    proc_cd_in IN VARCHAR2,
    proc_step_cd_in IN VARCHAR2,
    bch_dte_in IN DATE,
    fl_nbr_in IN VARCHAR2,
    verbose_log_flag_in IN INTEGER,
    pred_check_req_in IN INTEGER,
    error_code_1_in IN VARCHAR2,
    ibd_id_in IN INTEGER,
    proc_step_status_out OUT INTEGER,
    sp_hier_inout IN OUT VARCHAR2);
    PROCEDURE APPEND_EXPOSE (job_name_in IN VARCHAR2,
    schema_name_in IN VARCHAR2,
    proc_cd_in IN VARCHAR2,
    proc_step_cd_in IN VARCHAR2,
    bch_dte_in IN DATE,
    data_grp_cde_in IN VARCHAR2,
    verbose_log_flag_in IN INTEGER,
    pred_check_req_in IN INTEGER,
    ibd_id_in IN INTEGER,
    proc_step_status_out OUT INTEGER,
    sp_hier_inout IN OUT VARCHAR2);
    END ODS_APPEND_REPLACE;
    CREATE OR REPLACE
    PACKAGE BODY SEODS02.ODS_APPEND_REPLACE
    AS
    PROCEDURE APPEND_REPLACE_INSERT (job_name_in IN VARCHAR2,
    schema_name_in IN VARCHAR2,
    proc_cd_in IN VARCHAR2,
    proc_step_cd_in IN VARCHAR2,
    bch_dte_in IN DATE,
    fl_nbr_in IN VARCHAR2,
    verbose_log_flag_in IN INTEGER,
    pred_check_req_in IN INTEGER,
    error_code_1_in IN VARCHAR2,
    ibd_id_in IN INTEGER,
    proc_step_status_out OUT INTEGER,
    sp_hier_inout IN OUT VARCHAR2)
    AS
    /* Local Variables Declaration*/
    v_curr_date DATE := CURRENT_DATE;
    v_procedure_name VARCHAR2(100):= 'APPEND_REPLACE_INSERT';
    v_stg_tbl VARCHAR2(100);
    v_act_tbl VARCHAR2(100);
    v_whr_clause_out VARCHAR2(1000);
    option_in VARCHAR2(30);
    v_common_col_list VARCHAR2(10000);
    v_stg_col_list VARCHAR2(10000);
    v_act_col_list VARCHAR2(10000);
    v_query VARCHAR2(10000);
    v_thrshld_query VARCHAR2(10000);
    v_actl_inpt_query VARCHAR2(10000);
    v_proc_step_stat_query VARCHAR2(10000);
    v_error_msg_in VARCHAR2(10000);
    v_part_val_out INTEGER;
    v_row_cnt NUMBER(10);
    v_cmit_nbr NUMBER(10);
    v_actl_inpt_cnt NUMBER(10);
    v_rec_inserted_cnt NUMBER(10);
    v_rec_errored_cnt NUMBER(10);
    v_thrshld_nbr NUMBER(10);
    v_data_grp_query VARCHAR2(10000);
    v_data_grp_cde VARCHAR2(30);
    v_proc_step_upd_out NUMBER(1);
    proc_step_start_out NUMBER(1);
    proc_step_status VARCHAR2(30);
    handled_exception EXCEPTION;
    BEGIN
    /* Enable the logging if verbose log flag is 0*/
    IF verbose_log_flag_in = 0 THEN
    DBMS_OUTPUT.ENABLE();
    ELSE
    DBMS_OUTPUT.DISABLE();
    END IF;
    /* Start the Append/Replace Update process step after all the predecessor process steps are complete */
    ODS_CONTROL_UTILITY.PROC_STEP_START( proc_cd_in => proc_cd_in,
    proc_step_cd_in => proc_step_cd_in,
    ibd_id_in => ibd_id_in,
    bch_dte_in => bch_dte_in,
    job_name_in => job_name_in,
    verbose_log_flag_in => verbose_log_flag_in,
    pred_chk_reqd_in => pred_check_req_in,
    proc_step_stat_out => proc_step_start_out,
    sp_hier_inout => sp_hier_inout);
    IF proc_step_start_out = 0 THEN
    dbms_output.put_line('Process Step '|| proc_step_cd_in ||' started for Process '||proc_cd_in);
    /*If process step is successfully started then get the active and stage table names */
    ODS_CONTROL_UTILITY.GET_TABLE_NAME( proc_cd_in => proc_cd_in,
    proc_step_in => proc_step_cd_in,
    ibd_id_in => ibd_id_in,
    actv_tbl_out => v_act_tbl,
    stg_tbl_out => v_stg_tbl,
    sp_hier_inout => sp_hier_inout);
    IF v_act_tbl IS NULL THEN
    v_error_msg_in := 'Active table name is null. Please check the parameters passed';
    option_in := 'others';
    RAISE handled_exception;
    /* If Active table is not null then get the active partition of the table*/
    ELSE
    dbms_output.put_line('Active table name is : '||v_act_tbl);
    v_data_grp_query := 'SELECT data_grp_cde
    FROM '||v_cntl_schema ||'.proc
    WHERE proc_id = '||chr(39)||proc_cd_in ||chr(39)||
    ' AND ibd_id = '||ibd_id_in;
    EXECUTE IMMEDIATE v_data_grp_query INTO v_data_grp_cde;
    ODS_CONTROL_UTILITY.GET_ACT_PART(tbl_name_in => v_act_tbl,
    data_grp_cde_in => v_data_grp_cde,
    meta_data_in => 'VIEW DYN METADATA',
    part_val_out => v_part_val_out,
    sp_hier_inout => sp_hier_inout);
    IF v_part_val_out IS NULL THEN
    v_error_msg_in := 'Incorrect table name ' || v_act_tbl;
    option_in := 'others';
    v_location := 20;
    RAISE handled_exception;
    END IF;
    dbms_output.put_line('Active partition for the table '|| v_act_tbl ||' is : '||v_part_val_out);
    /*Get the list of active table columns*/
    ODS_APPLICATION_UTILITY.GET_TAB_COLS (schema_name_in => schema_name_in,
    table_name_in => v_act_tbl,
    col_name_out => v_act_col_list,
    sp_hier_inout => sp_hier_inout);
    v_act_col_list := SUBSTR(v_act_col_list,1,LENGTH(v_act_col_list)-1);
    IF v_act_col_list IS NULL THEN
    v_error_msg_in := 'Failed fetching columns for ' || v_act_tbl || '. Check for the columns in table name';
    option_in := 'others';
    v_location := 30;
    RAISE handled_exception;
    /*Get the list of active table columns and concatenate the columns with 'stg_array(i)' */
    ELSE
    dbms_output.put_line('Active Table Columns List: '||v_act_col_list);
    ODS_APPLICATION_UTILITY.GET_TAB_COLS (schema_name_in => schema_name_in,
    table_name_in => v_act_tbl,
    identifier_name_in => 'stg_array(i)',
    col_name_out => v_common_col_list,
    sp_hier_inout => sp_hier_inout);
    v_common_col_list := SUBSTR(v_common_col_list,1,LENGTH(v_common_col_list)-1);
    IF v_common_col_list IS NULL THEN
    v_error_msg_in := 'Failed fetching columns for ' || v_act_tbl || ' and get concatenated with ' || 'STTG_ARRAY' ||'. Check for the columns in table name';
    option_in := 'others';
    v_location := 40;
    RAISE handled_exception;
    ELSE
    ODS_APPLICATION_UTILITY.GET_TAB_COLS (schema_name_in => schema_name_in,
    table_name_in => v_stg_tbl,
    col_name_out => v_stg_col_list,
    sp_hier_inout => sp_hier_inout);
    v_stg_col_list := SUBSTR(v_stg_col_list,1,LENGTH(v_stg_col_list)-1);
    IF v_stg_col_list IS NULL THEN
    v_error_msg_in := 'Failed fetching columns for ' || v_stg_tbl || '. Check for the columns in table name';
    option_in := 'others';
    v_location := 50;
    RAISE handled_exception;
    ELSE
    /* Form the WHERE clause on the primary key columns to update the proc_flag
    column of appropriate record in stage table */
    ODS_APPLICATION_UTILITY.GET_WHERE_CLAUSE( schema_nme_in => schema_name_in,
    tbl_nme_in => v_stg_tbl,
    trg_id => 'stg_array(i)',
    whr_clause_out => v_whr_clause_out,
    sp_hier_inout => sp_hier_inout);
    IF v_whr_clause_out IS NULL THEN
    v_error_msg_in := 'No columns fetched for ' || v_stg_tbl || '. Check for the columns in table name';
    option_in := 'others';
    v_location := 60;
    RAISE handled_exception;
    ELSE
    dbms_output.put_line('Where Clause is : ' || v_whr_clause_out );
    v_thrshld_query := 'SELECT proc_step_thrshld_nbr FROM '|| v_cntl_schema ||'.proc_step
    WHERE proc_id = '|| chr(39) ||proc_cd_in|| chr(39) ||
    ' AND proc_step_cde = '|| chr(39) ||proc_step_cd_in|| chr(39) ||
    ' AND ibd_id = ' || ibd_id_in;
    EXECUTE IMMEDIATE v_thrshld_query INTO v_thrshld_nbr;
    dbms_output.put_line('Threshold number for the process step '||proc_step_cd_in||' is '||v_thrshld_nbr||' for the process '||proc_cd_in);
    END IF;
    END IF;
    END IF;
    END IF;
    END IF;
    v_query := 'SELECT proc_cmit_nbr FROM '||v_cntl_schema||'.proc
    WHERE proc_id = '|| chr(39) || proc_cd_in || chr(39) ||
    ' AND ibd_id = '|| ibd_id_in;
    EXECUTE IMMEDIATE v_query INTO v_cmit_nbr;
    IF v_part_val_out = 999 THEN
    /* Execute the dynamic pl/sql block to append the data to the active table*/
    dbms_output.put_line('Executing Dynamic Insert Block for Append Paradigm');
    dbms_output.put_line('--------------------------------------------------');
    v_location := 80;
    EXECUTE IMMEDIATE q'{
    DECLARE
    v_rec_inserted_cnt_in NUMBER(10):=0;
    error_msg_in VARCHAR2(1000);
    v_dyn_proc_step_upd_out NUMBER(1);
    v_rec_updt_cnt_in NUMBER(10):=0;
    v_actl_inpt_cnt NUMBER(10):=0;
    v_rec_errored_cnt_in NUMBER(10):=0;
    v_dyn_option_in VARCHAR2(30);
    v_dyn_sp_hier VARCHAR2(30);
    v_dyn_handled_exception EXCEPTION;
    v_dyn_verbose_flag NUMBER(1):=0;
    CURSOR c IS
    SELECT }' || v_stg_col_list ||
    ' FROM ' || v_stg_tbl ||
    ' WHERE fl_nbr = ' || fl_nbr_in ||
    ' AND proc_flag = ' || chr(39) || 'N' || chr(39) ||
    ' AND to_date(bch_dte,'||CHR(39)||'DD-MON-YY'||CHR(39)||') <= '||CHR(39)|| bch_dte_in || CHR(39)||q'{;
    TYPE array IS TABLE OF c%ROWTYPE;
    stg_array array;
    BEGIN
    /* Enable the logging if verbose log flag is 0*/
    IF v_dyn_verbose_flag = }' || verbose_log_flag_in || q'{ THEN
    DBMS_OUTPUT.ENABLE();
    END IF;
    OPEN c;
    LOOP
    FETCH c BULK COLLECT INTO stg_array LIMIT }'|| v_cmit_nbr ||q'{;
    FOR i IN 1..stg_array.COUNT LOOP
    BEGIN
    INSERT INTO }' || schema_name_in || q'{.}'|| v_act_tbl || q'{( }'|| v_act_col_list ||q'{,crte_pgm, updt_pgm, crte_tstp, updt_tstp, expsd_rec_ind) VALUES }' || q'{ ( }' || v_common_col_list || q'{,'}' || job_name_in || q'{','}' || job_name_in ||q'{','}' || v_curr_date ||q'{','}' || v_curr_date||q'{','N' );}' ||
    q'{
    v_rec_inserted_cnt_in := v_rec_inserted_cnt_in + 1 ;
    v_actl_inpt_cnt := v_actl_inpt_cnt + 1 ;
    error_msg_in := 'Error in updating PROC_STAT as inserted';
    UPDATE }' || schema_name_in || q'{.}' || v_stg_tbl || q'{
    SET proc_flag = 'I' ,
    updt_pgm = '}' || job_name_in || q'{',
    updt_tstp = '}' || v_curr_date || q'{'
    WHERE }'|| v_whr_clause_out ||q'{;
    EXCEPTION
    WHEN DUP_VAL_ON_INDEX THEN
    error_msg_in := 'Record duplicated';
    v_actl_inpt_cnt := v_actl_inpt_cnt + 1 ;
    v_rec_errored_cnt_in := v_rec_errored_cnt_in + 1;
    IF v_rec_errored_cnt_in >}' || v_thrshld_nbr || q'{ THEN
    error_msg_in := 'Threshold limit }' || v_thrshld_nbr || q'{ Reached';
    v_dyn_option_in := 'proc_step';
    RAISE v_dyn_handled_exception;
    ELSE
    error_msg_in := 'Error in updating PROC_STAT as error';
    UPDATE }' || schema_name_in || q'{.}' || v_stg_tbl || q'{
    SET proc_flag = 'E',
    -- err_code = }' || error_code_1_in || q'{, --need to uncomment once the err_code column is created in stage table
    updt_pgm = '}' || job_name_in || q'{',
    updt_tstp = '}' || v_curr_date || q'{'
    WHERE }'|| v_whr_clause_out ||q'{;
    END IF;
    END;
    END LOOP;
    EXIT WHEN c%NOTFOUND;
    END LOOP;
    CLOSE c;
    ND ODS_APPEND_REPLACE;
    /

    DUPLICATE
    Any suggestions about this program to improve performance and effective cod

  • User exit for  this code

    Hi ..
    my requirement  is the program should prompt for 3 parameters (all check marks) with the follwoing text; all check marks enabled by default
    - Variables
    - Key Figures
    - Structures
    So when users select variables then do this part in main program
    test_for = 'STR'.
    perform dowork using test_for.
    for key figures
    test_for = 'CKF'.
    perform dowork using test_for.
    test_for = 'SEL'.
    perform dowork using test_for.
    for variables
    test_for = 'VAR'.
    perform dowork using test_for.
    please give  the code how to write that one.
    thanks in advance
    Madhavi

    Hi Maik,
    am using this quode for one tool .this tool is used for copy queries from one system another instead of transporting.its easy method.so i want to do some modifications for this code.please elaborate ur answer .will assign points.
    Cheers,
    Madhavi

  • Checking my Pivot Code please

    I'll never cope with the pivot. May you check this code please guys...:
    select * from archivebilled
    pivot ( sum([month charge]) for [element code] in ('august','september','october','december'))
    Incorrect syntax near august

    Leave out the As clause.  Put the as alias in the Select statement.
    select
    [august] as Ageste
    , [september] as Septe
    ,[october] as Ottobered
    ,[november] as Nove
    .[december] as Dicombero
    , * from archivebilled
    pivot ( sum([element charge]) for [element code] in ([august]
    ,[september]
    ,[october]
    ,[november]
    ,[december] ) as ele
    Russel Loski, MCT, MCSE Data Platform/Business Intelligence. Twitter: @sqlmovers; blog: www.sqlmovers.com

  • Please give a comment on this program.

    This program is to find a product, size and color. It is abstract program.
    abstract class Pants{
    protected string pro_code;
    protected int size=0;
    protected string color;
    boolean sizeIs(string s)
    boolean colorIs(string c)
    boolean buttonFront(string b)
    public Pants(string p, int s, string c){
    pro_code=p; size=s; color = c;}
    public boolean size( ){
    s.size=sizeIs;
    system.out.println("size");
    if(sizeIs ==true)
    system.out.println(sizeIs);
    public boolean color( ){
    colour = colorIs;
    system.out.println("color");
    if(colourIs = true)
    system.out.println(color)
    public boolean buttonFront( ){
    if(buttonFront ==true)
    system.out.println("zipper");
    else
    system.out.println("button");
    public class test{
    public static void main (string[ ]args){
    system.out.println("Input Product code:");
    p.pro_code;
    Pants p = newPants[2];
    Pants p1 = newPants[2];
    for (int i = 0; i<=2; i++){
    system.out.println(p.pro_code + p.size +p.color)
    system.out.println(p1.pro_code + p1.size +p1.color)
    }

    before I comment on the code, its better to ask the compiler, since compiler is one whose comments really matter, so please try to compile your code first.
    Secondly which aspect you want your code to be reviewed from :
    Readability
    Maintainabilty
    Reusability
    From an OO perspective or otherwise. Your question is too generic in nature

  • URGENT Check this code for me please

    Dear whoeverthisreads, please read and see at the bottom my sourcecode, or whatever I could make of it until (even with help) I failed to see any solution. Please copy, paste and run to see if you can manage to adjust the program to make it work in the way as described. And I think I made it unnecessarily complicated. Whatever you can do for me, I will be very, very grateful.
    Prem Pradeep, email: [email protected]
    (A beginning dutch Java student who is running out of time and hope)
    Catalogue Manager
    Specification:
    a) Develop an object to represent to encapsulate an item in a catalogue. Each CatalogueItem has three pieces of information: an alphanumeric catalogue code, a name, and a price (in dollars and cents), that excludes sales tax. The object should also be able to report the price, inclusive of a 15% sales tax, and the taxed component of the price.
    b) Work out a way to be able to support the inc tax/ex tax price accessors, and the tax component accessor, without needing to store any additional information in the object.
    c) Use an array of 5 CatalogueItem items to store data. (You may assume that no imported goods will be recorded.)
    d) Write a driver program that prompts for three sets of user input (catalogue number, description and price), to be stored in the atalogueItem instance.
    e) The data are to be read for each item in a single line. The data lines will be in the format:
    CatNo:Description:Price
    Use a StringTokenizer object to separate these data lines into their components.
    f) Review the class definition of CatalogueItem, and use modifiers where appropriate to:
    � Ensure that data is properly protected;
    � Ensure that the accessors and mutators are most visible;
    � The accessors and mutators for the catalogue number and description cannot be overridden.
    � The constant for the tax rate is publicly accessible, and does not need an instance of the class
    present in order to be accessible.
    As well as a summary, the program should also calculate and display:
    � All of the cheapest and most expensive item(s) in the catalogue. In the case of more than one
    item being the cheapest (or most expensive), they should all be listed.
    � A total of the pre-tax worth of the goods in the catalogue.
    � The average amount of tax on the items in the catalogue.
    A sample execution of the program may be as follows (output should be tabulated):
    Enter five items of data:
    AA123: Telephone: 52.00
    ZJ282: Pine Table: 98.00
    BA023: Headphones: 23.00
    ZZ338: Wristwatch: 295.00
    JW289: Tape Recorder: 23.00
    LISTING OF ALL GOODS
    Cat      Description      ExTax           Tax           IncTax ~
    ZJ282      pine Table           98.00           14.70           112.70
    AA123 Telephone           52.00           7.80           59.80
    BA023 Headphones      23.00           3.45           26.45
    ZZ338      Wristwatch      295.00      44.25      339.25
    JW289 Tape Recorder      23.00           3.45           26.45
    CHEAPEST GOODS IN CATALOGUE
    Cat      Description      ExTax           Tax           IncTax
    BA023 Headphones           23.00           3.45           26.45
    JW289 Tape Recorder      23.00           3.45           26.45
    MOST EXPENSIVE GOODS IN CATALOGUE
    Cat      Description      ExTax           Tax           IncTax
    ZZ338      Wristwatch      295.00      44.25      339.25
    TOTAL PRE-TAX WORTH OF CATALOGUE ITEMS:      491.00
    AVERAGE AMOUNT OF TAX PAYABLE PER ITEM:      14.73
    The next code is what I could make of it�until I got terribly stuck...
    //CatalogueItem.java
    import java.io.*;
    import java.text.DecimalFormat;
    import java.util.StringTokenizer;
    public class CatalogueItem {
    private static final double TAXABLE_PERCENTAGE = 0.15;
    private String catalogNumber;
    private String description;
    private double price;
    /** Creates a new instance of CatalogueItem */
    public CatalogueItem() {
    catalogNumber = null;
    description = null;
    price = 0;
    public CatalogueItem(String pCatalogNumber, String pDescription, double pPrice) {
    catalogNumber = pCatalogNumber;
    description = pDescription;
    price = pPrice;
    void setCatalogNumber(String pCatalogNumber) {
    catalogNumber = pCatalogNumber;
    String getCatalogNumber() {
    String str = catalogNumber;
    return str;
    void setDescription(String pDescription) {
    description = pDescription;
    String getDescription() {
    String str = description;
    return str;
    void setPrice(String pPrice) {
    price = Double.parseDouble(pPrice);
    double getPrice() {
    double rprice = price;
    return formatDouble(rprice);
    double getTaxAmount(){
    double rTaxAmount = price * TAXABLE_PERCENTAGE;
    return formatDouble(rTaxAmount);
    double getIncTaxAmount() {
    double rTaxAmount = price * (1 + TAXABLE_PERCENTAGE);
    return formatDouble(rTaxAmount);
    double formatDouble(double value) {
    DecimalFormat myFormatter = new DecimalFormat("###.##");
    String str1 = myFormatter.format(value);
    // System.out.println("String is " + str1);
    // System.out.println("The format value : " + value);
    return Double.parseDouble(str1);
    public static void main(String[] args) throws IOException {
    final int MAX_INPUT_SET = 5;
    final String strQ = "Enter five items of data:";
    CatalogueItem[] catalogList = new CatalogueItem[MAX_INPUT_SET];
    String strInput;
    BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
    String header = "Cat\tDescription\tExTax\tTax\tInc Tax";
    String lines = "---\t-----------\t------\t---\t-------";
    // Input of five items with three data each, delimiter ":"
    for (int i = 0; i < MAX_INPUT_SET; i++) {
    catalogList[i] = new CatalogueItem();
    System.out.print(strQ);
    strInput = stdin.readLine();
    StringTokenizer tokenizer = new StringTokenizer(strInput, ":" );
    String inCatNo = tokenizer.nextToken();
    String inDescr = tokenizer.nextToken();
    String inPrice = tokenizer.nextToken();
    catalogList.setCatalogNumnber(inCatNo);
    catalogList[i].setDescription(inDescr);
    catalogList[i].setPrice(inPrice);
    // Listing of all goods
    System.out.println("LISTING OF ALL GOODS");
    System.out.println(header);
    System.out.println(lines);
    for (int i = 0; i < MAX_INPUT_SET; i++) {
    System.out.println(
    catalogList[i].getCatalogNumber() + "\t" +
    catalogList[i].getDescription() + "\t" +
    catalogList[i].getPrice() + "\t" +
    catalogList[i].getTaxAmount() + "\t" +
    catalogList[i].getIncTaxAmount());
    // This should pick the cheapest and most expensive goods in catalogue, but
    // this code is not good:
    // In the case of more than one item being the cheapest (or most expensive),
    // they should all be listed.
    double cheapest = cataloguelist[1].getPrice();
    double mostExpensive = cataloguelist[1].getPrice();
              for(int i=2; i< MAX_INPUT_SET; i++){
                   if (cataloguelist[i].getPrice < cheapest)
              cheapest = i;}
              for(int i=2; i< MAX_INPUT_SET; i++){
                   if (cataloguelist[i].getPrice > mostExpensivet)
              mostExpensive = i;}
    // Lists cheapest goods (not complete enough)
    i = cheapest;
    System.out.println("CHEAPEST GOODS IN CATALOGUE");
    System.out.println(header);
    System.out.println(lines);
    System.out.println(
    catalogList[i].getCatalogNumber() + "\t" +
    catalogList[i].getDescription() + "\t" +
    catalogList[i].getPrice() + "\t" +
    catalogList[i].getTaxAmount() + "\t" +
    catalogList[i].getIncTaxAmount());
    // Lists most expensive goods (not complete enough)
    i = mostExpensive;
    System.out.println("MOST EXPENSIVE GOODS IN CATALOGUE");
    System.out.println(header);
    System.out.println(lines);
    System.out.println(
    catalogList[i].getCatalogNumber() + "\t" +
    catalogList[i].getDescription() + "\t" +
    catalogList[i].getPrice() + "\t" +
    catalogList[i].getTaxAmount() + "\t" +
    catalogList[i].getIncTaxAmount());}}
    // Generates and shows total pre-tax worth of catalogue items (how??)
    // generates and shows amount of tax payable per item (how??)

    How is this:
    import java.io.*;
    import java.text.*;
    import java.util.*;
    public class Cat
         Vector items = new Vector();
    public Cat()
    public void read(String fname)
         FileReader     fr;
        BufferedReader br;
         String         str ="";
        try
             fr = new FileReader(fname);
            br = new BufferedReader(fr);
            while ((str = br.readLine()) != null && items.size() < 30)
                   if (!str.trim().equals(""))
                        StringTokenizer tokenizer = new StringTokenizer(str, ":");
                     String n = tokenizer.nextToken().trim();
                        String d = tokenizer.nextToken().trim();
                        String s = tokenizer.nextToken().trim();
                        double p = Double.parseDouble(s);
                        items.add(new Item(n,d,p));
            fr.close();
        catch (FileNotFoundException e)
            System.out.println("Input file cannot be located, please make sure the file exists!");
            System.exit(0);
        catch (IOException e)
            System.out.println(e.getMessage());
            System.out.println("Application cannot read the data from the file!");
            System.exit(0);
    public void displayAll()
         for (int j=0; j < items.size(); j++)
              Item item = (Item)items.get(j);
              System.out.println(item.toString());
    public void sort()
         Collections.sort(items);     
    public class Item implements Comparable
         String       number, description;
         double       price,pricep;
         final double TAXRATE = 0.15;
    public Item(String number, String description, double price)
         this.number      = number;
         this.description = description;
         this.price       = price;
         this.pricep      = price * TAXRATE;
    public int compareTo(Object o1)
         String o = ((Item)o1).number;
         return(number.compareTo(o));
    public String toString()
         DecimalFormat df = new DecimalFormat("#.00");     
         String        p1 = df.format(TAXRATE*price);
         String        p2 = df.format(TAXRATE*price+price);
         String s = number+"\t "+description+"\t"+price+"\t"+p1+"\t"+p2+"\t" ;
         return(s);
    public static void main (String[] args)
         Cat catalog = new Cat();
         catalog.read("C31.dat");
         String reply = "";
         BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
         while (!reply.equals("e"))
              System.out.println("");
            System.out.println("CATALOGUE MANAGER: MAIN MENU");
            System.out.println("============================");
            System.out.println("a) display all goods        b) display cheapest/dearest goods");
            System.out.println("c) sort the goods list      d) search the good list");
            System.out.println("e) quit");
            System.out.print("Option:");
              try
                   reply = stdin.readLine();
              catch (IOException e)
                System.out.println("ERROR:" + e.getMessage());
                System.out.println("Application exits now");
                System.exit(0);
              if (reply.equals("a")) catalog.displayAll();
              if (reply.equals("c")) catalog.sort();
    Noah

  • Please give me flowchart for this code...

    Writing a Java applet to communicate with a serial device attached to the Device
    Server is very straightforward. However, familiarity with Java programming and a
    Java compiler are required.
    As with any network application, open a communication channel to the remote
    device. In our example, a socket is opened and and two data streams are created to
    perform the actual sending and receiving of data.
    The following example uses a new Java Class called tcpip. Copy the following code
    into a file called tcpip.java.
    import java.*;
    import java.lang.*;
    import java.net.*;
    import java.util.*;
    import java.io.*;
    * This class opens a TCP connection, and allows reading and writing of byte
    arrays.
    public class tcpip
    protected Socket s = null;
    public DataInputStream dis = null;
    protected DataOutputStream dos = null;
    public tcpip(InetAddress ipa, int port)
    Socket s1 = null;
    try { // Open the socket
    s1 = new Socket(ipa.getHostAddress(), port);
    catch (IOException e) {
    System.out.println("Error opening socket");
    return;
    s = s1;
    try { // Create an input stream
    dis = new DataInputStream(new
    BufferedInputStream(s.getInputStream()));
    catch(Exception ex) {
    System.out.println("Error creating input stream");
    try { // Create an output stream
    dos = new DataOutputStream(new
    BufferedOutputStream(s.getOutputStream()));
    catch(Exception ex) {
    System.out.println("Error creating output stream");
    public synchronized void disconnect()
    if (s != null) {
    try {
    s.close();
    catch (IOException e){}
    public synchronized void send(byte[] temp)
    try {
    dos.write(temp, 0, temp.length);
    dos.flush();
    catch(Exception ex) {
    System.out.println("Error sending data : " + ex.toString());
    public synchronized void send(byte[] temp, int len)
    try {
    dos.write(temp, 0, len);
    dos.flush();
    catch(Exception ex) {
    System.out.println("Error sending data : " + ex.toString());
    public synchronized void send(String given)
    // WARNING: this routine may not properly convert Strings to bytes
    int length = given.length();
    byte[] retvalue = new byte[length];
    char[] c = new char[length];
    given.getChars(0, length, c, 0);
    for (int i = 0; i < length; i++) {
    retvalue[i] = (byte)c;
    send(retvalue);
    public synchronized byte[] receive()
    byte[] retval = new byte[0];
    try {
    while(dis.available() == 0); /* Wait for data */
    catch (IOException e){}
    try {
    retval = new byte[dis.available()];
    catch (IOException e){}
    try {
    dis.read(retval);
    catch (IOException e){}
    return(retval);
    public int available()
    int avail;
    avail = 0;
    try {
    avail = dis.available();
    catch (IOException e) {}
    return(avail);
    Next, create the Text_io class as the application. Copy the following code
    into a file called �Text_io.java�.
    import java.awt.*;
    import java.awt.event.*;
    import java.lang.*;
    public class Text_io extends Panel implements Runnable,
    TextListener {
    private tcpip gtp;
    String oldmessage = new String("");
    TextArea input_box = new TextArea("", 10, 60, 3);
    TextArea output_box = new TextArea("", 10, 60, 3);
    Thread timer;
    public Text_io(tcpip tp) {
    gtp = tp;
    setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
    c.insets = new Insets(5,5,5,5);
    setBackground(java.awt.Color.lightGray);
    setSize(561,380);
    c.gridx = 0; c.gridy = 2; c.gridwidth = 1; c.gridheight =
    1;
    c.weightx = 0.0; c.weighty = 0.0; c.anchor =
    GridBagConstraints.WEST;
    c.fill = GridBagConstraints.NONE;
    add((new Label("To Device Server: (Type Here--->)")), c);
    //input_box
    input_box.addTextListener(this);
    c.gridx = 1; c.gridy = 2; c.gridwidth = 3; c.gridheight =
    1;
    c.weightx = 0.5; c.weighty = 0.0; c.anchor =
    GridBagConstraints.CENTER;
    c.fill = GridBagConstraints.BOTH;
    add(input_box,c);
    c.gridx = 0; c.gridy = 4; c.gridwidth = 1; c.gridheight =
    1;
    c.weightx = 0.0; c.weighty = 0.0; c.anchor =
    GridBagConstraints.WEST;
    c.fill = GridBagConstraints.NONE;
    add((new Label("From Device Server:")), c);
    c.gridx = 1; c.gridy = 4; c.gridwidth = 3; c.gridheight =
    1;
    c.weightx = 0.5; c.weighty = 0.0; c.anchor =
    GridBagConstraints.CENTER;
    c.fill = GridBagConstraints.BOTH;
    add(output_box,c);
    output_box.setEditable(false);
    timer = new Thread(this);
    timer.start();
    public void run() {
    int i;
    byte[] in;
    Thread me = Thread.currentThread();
    while (timer == me) {
    try {
    Thread.currentThread().sleep(200);
    catch (InterruptedException e) { }
    if ( (gtp != null) && ((i = gtp.available()) > 0) ) {
    in = gtp.receive();
    /* remove non-printing bytes */
    for (i = 0; i < in.length; i++) {
    if (in[i] < 0x20)
    in[i] = 0x20;
    output_box.append((new String(in)));
    public void textValueChanged(TextEvent e) {
    int len, i;
    String str = new String("");
    String message = input_box.getText();
    len = message.length() - oldmessage.length();
    if (len < 0) {
    for (i = 0; i < -len; i++)
    str += "\b";
    //System.out.println("Backspace");
    else if (len > 0) {
    str = message.substring(oldmessage.length());
    //System.out.println("len = "+str.length()+" str =
    "+str);
    oldmessage = message;
    if ( (len != 0) && (gtp != null) )
    gtp.send(str);
    Next, create the actual applet that uses the tcpip and Text_io classes. Copy
    the following code into a file called �Test.java�.
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.Applet;
    import java.net.*;
    import java.io.*;
    import java.lang.*;
    import java.text.*;
    import java.util.*;
    public class Test extends Applet {
    static private boolean isapplet = true;
    static private InetAddress arg_ip = null;
    static private int arg_port = 0;
    public tcpip gtp = null;;
    InetAddress reader_ip = null;
    int port = 10001;
    public void init()
    gtp = null;
    reader_ip = null;
    port = 10001;
    public void start()
    String st = new String("TCP/IP connection status: ");
    setFont(new Font("Dialog",Font.BOLD,16));
    setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
    c.gridx = 0; c.gridy = 0; c.gridwidth = 1; c.gridheight
    = 1;
    c.anchor = GridBagConstraints.CENTER;
    c.fill = GridBagConstraints.BOTH;
    c.insets = new Insets(5,5,5,5);
    setBackground(Color.yellow);
    setSize(600,500);
    /* Either get the IP address from the HTTP server if
    we're an applet, or from the commandline (if passed).
    if (isapplet) {
    try{
    reader_ip = InetAddress.getByName(getCodeBase().getHost());
    catch (UnknownHostException e){}
    else {
    reader_ip = arg_ip;
    if (arg_port != 0) {
    port = arg_port;
    /* Open a socket to the Device Server's serial port
    if (reader_ip != null) {
    if (gtp == null) {
    gtp = new tcpip(reader_ip, port);
    if (gtp.s == null) {
    st += "Connection FAILED! ";
    gtp = null;
    if (gtp == null) {
    st += "Not Connected";
    add((new Label(st)), c);
    return;
    st += "Connected";
    add((new Label(st)), c);
    /* You may now perform IO with the Device Server via
    * gtp.send(byte[] data_out);
    * byte[] data_in = gtp.receive();
    * functions.
    * In our example we'll use two TextBoxes which have
    * been extended to handle IO to the Device Server.
    *Data typed in the upper text box will be sent to
    * the Device Server, and data received will be
    *displayed in the lower text box.
    /* Start of custom application code */
    /* ADD YOUR CODE HERE */
    c.gridx = 0; c.gridy = 2; c.gridwidth = 3; c.gridheight =
    1;
    c.anchor = GridBagConstraints.WEST;
    add((new Text_io(gtp)), c);
    /* End of custom application code */
    public void destroy()
    if (gtp != null)
    gtp.disconnect();
    gtp = null;
    public void stop() {
    public static void main(String[] args) {
    Frame frame = new Frame("TCP/IP Test");
    frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    if (args.length > 0) {
    try{
    arg_ip = InetAddress.getByName(args[0]);
    catch (UnknownHostException e){}
    if (args.length > 1) {
    try {
    arg_port = Integer.valueOf(args[1]).intValue();
    catch (NumberFormatException e) {}
    Test ap = new Test();
    frame.add(ap);
    ap.init();
    isapplet = false;
    ap.start();
    frame.pack();
    frame.show();

    Let's see a decent try by you towards a solution first. I've found that usually the more thought and effort posters put into creating and solving their questions, the better their chances are of a volunteer here taking the time and effort to consider it and give a helpful answer. In other words, show that you are putting effort into doing your own homework first.
    Also, when posting your code, please use code tags so that your code will retain its formatting and be readable. To do this, you will need to paste already formatted code into the forum, highlight this code, and then press the "code" button at the top of the forum Message editor prior to posting the message. You may want to click on the Preview tab to make sure that your code is formatted correctly. Another way is to place the tag &#91;code] at the top of your block of code and the tag &#91;/code] at the bottom, like so:
    &#91;code]
      // your code block goes here.
      // note the differences between the tag at the top vs the bottom.
    &#91;/code]or
    {&#99;ode}
      // your code block goes here.
      // note here that the tags are the same.
    {&#99;ode}good luck

  • Can anyone please explain this code to me?

    I am a new (junior)programmer?Can anyone please explain this code to me in lame terms? I am working at a client location and found this code in a project.
    _file name is AtccJndiTemplate.java_
    Why do we use the Context class?
    Why do we use the properties class?
    package org.atcc.common.utils;
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.Properties;
    import java.util.logging.Logger;
    import javax.naming.Context;
    import javax.naming.InitialContext;
    import javax.naming.NamingException;
    import org.springframework.jndi.JndiTemplate;
    public class AtccJndiTemplate extends JndiTemplate
      private static Logger logger = Logger.getLogger(AtccJndiTemplate.class.getName());
      private String jndiProperties;
      protected Context createInitialContext()
        throws NamingException
        Context context = null;
        InputStream in = null;
        Properties env = new Properties();
        logger.info("Load JNDI properties from classpath file " + this.jndiProperties);
        try
          in = AtccJndiTemplate.class.getResourceAsStream(this.jndiProperties);
          env.load(in);
          in.close();
        catch (NullPointerException e) {
          logger.warning("Did not read JNDI properties file, using existing properties");
          env = System.getProperties();
        } catch (IOException e) {
          logger.warning("Caught IOException for file [" + this.jndiProperties + "]");
          throw new NamingException(e.getMessage());
        logger.config("ENV: java.naming.factory.initial = " + env.getProperty
    ("java.naming.factory.initial"));
        logger.config("ENV: java.naming.factory.url.pkgs = " + env.getProperty
    ("java.naming.factory.url.pkgs"));
        logger.info("ENV: java.naming.provider.url = " + env.getProperty
    ("java.naming.provider.url") + " timeout=" + env.getProperty("jnp.timeout"));
        context = new InitialContext(env);
        return context;
      public String getJndiProperties()
        return this.jndiProperties;
      public void setJndiProperties(String jndiProperties)
        this.jndiProperties = jndiProperties;
    }

    Hi,
    JNDI needs some property such as the
    java.naming.factory.initial
    java.naming.provider.url
    which are needed by the
    InitialContext(env);
    where env is a properties object
    Now if you can not find the physical property file on the class path
    by AtccJndiTemplate.class.getResourceAsStream(this.jndiProperties);
    where the String "jndiProperties" get injected by certain IOC ( inverse of control container ) such as Spring framework
    if not found then it will take the property from the system which will come from the evniromental variables which are set during the application start up i.e through the command line
    java -Djava.naming.factory.initial=com.sun.jndi.ldap.LdapCtxFactory -Danother=value etc..
    I hope this could help
    Regards,
    Alan Mehio
    London,UK

  • Please explain this code,this is regarding to ODS activation.

    Hi,
        Please I am unable to understand this code,this exists initial activation of ODS,please can anyone please explain me this
    ob started
    Step 001 started (program RSPROCESS, variant &0000000055152, user ID ALEREMOTE)
    Activation is running: Data target ZYL_O82, from 1.165.349 to 1.165.349
    Data to be activated successfully checked against archiving objects
    SQL: 20.06.2007 05:34:26 ALEREMOTE
    ANALYZE TABLE "/BIC/AZYT_O6240" DELETE STATISTICS
    SQL-END: 20.06.2007 05:34:26 00:00:00
    SQL: 20.06.2007 05:34:26 ALEREMOTE
    BEGIN DBMS_STATS.GATHER_TABLE_STATS ( OWNNAME =>
    'SAPR3', TABNAME => '"/BIC/AZYT_O6240"',
    ESTIMATE_PERCENT => 1 , METHOD_OPT => 'FOR ALL
    INDEXED COLUMNS SIZE 75', DEGREE => 1 ,
    GRANULARITY => 'ALL', CASCADE => TRUE ); END;
    Thanks & Regards,
    Mano

    Hi,
        Please I am unable to understand this code,this exists initial activation of ODS,please can anyone please explain me this
    ob started
    Step 001 started (program RSPROCESS, variant &0000000055152, user ID ALEREMOTE)
    Activation is running: Data target ZYL_O82, from 1.165.349 to 1.165.349
    Data to be activated successfully checked against archiving objects
    SQL: 20.06.2007 05:34:26 ALEREMOTE
    ANALYZE TABLE "/BIC/AZYT_O6240" DELETE STATISTICS
    SQL-END: 20.06.2007 05:34:26 00:00:00
    SQL: 20.06.2007 05:34:26 ALEREMOTE
    BEGIN DBMS_STATS.GATHER_TABLE_STATS ( OWNNAME =>
    'SAPR3', TABNAME => '"/BIC/AZYT_O6240"',
    ESTIMATE_PERCENT => 1 , METHOD_OPT => 'FOR ALL
    INDEXED COLUMNS SIZE 75', DEGREE => 1 ,
    GRANULARITY => 'ALL', CASCADE => TRUE ); END;
    Thanks & Regards,
    Mano

  • Please Find the error in this code

    Hi ,  I am new to ajax.My problem is that i cannot insert a value in to a textfield which is fetched from a database(MySql).  I have two jsp pages.Definition1.jsp and definition.jsp. I am giving the code below.[b]But it does not work[/b]. I don't know where is the problem. I am using Mozilla Firefox..  [b]Definition1.jsp[/b]  <html>  <%@ page language="java"%>  <%@page contentType="text/html" %>   <script language="Javascript" type="text/javascript">   function createRequestObject() { var tmpXmlHttpObject;   if (window.XMLHttpRequest) {   tmpXmlHttpObject = new XMLHttpRequest();       } else if (window.ActiveXObject) {   tmpXmlHttpObject = new ActiveXObject("Microsoft.XMLHTTP"); }  return tmpXmlHttpObject; }  //call the above function to create the XMLHttpRequest object var http = createRequestObject();  function makeGetRequest(wordId) { //make a connection to the server ... specifying that you intend to make a GET request  //to the server. Specifiy the page name and the URL parameters to send http.open('get','definition.jsp?id='+wordId);       //assign a handler for the response http.onreadystatechange = processResponse;       //actually send the request to the server http.send(null); }  function processResponse() { //check if the response has been received from the server if(http.readyState == 4){       //read and assign the response from the server           var result2 = http.responseText;  var result = http.responseXML.documentElement;                  //do additional parsing of the response, if needed            //in this case simply assign the response to the contents of the <div> on the page.  document.getElementById('description').innerHTML = result2;//[b]this works correctly[/b]           alert(result.getElementByTagName('p')[0].childNodes[0].nodeValue);//nothing happends here            document.getElementById('name').value=result.getElementsByTagName('p')[0].childNodes[0].nodeValue;           [u][b]//above code does not works and this is my problem[/b][/b[/u]] } }   </script> <body>  <form> <input type="text" id="name" size=10 value=" "></input>  </form> <h1>Have you heard these terms before?</h1>  Ceraunophobia More about Ceraunophobia<br> Astraphobia More about Astraphobia<br>   <div id="description">  </div>  </body>  </html>     [b]Definition.jsp[/b]    <%@ page language="java"%><%@ page import="java.sql.*,java.io.*,java.util.*,javax.servlet.*"%> <?xml version="1.0" encoding="UTF-8"?>  <% response.setContentType("text/xml"); response.setHeader("Cache-Control", "no-cache"); response.setHeader("pragma","no-cache"); Class.forName("com.mysql.jdbc.Driver").newInstance(); Connection con=DriverManager.getConnection("jdbc:mysql://itserver:3306/manzor?user=root&password="); Statement st= con.createStatement(); Statement st1= con.createStatement();  ResultSet rs,rs1; String id=request.getParameter("id");  rs=st.executeQuery("select * from user where USERTYPE='"+id+"'");  if(rs.next()){    %>  // p tag is here , can't display it //<p> <p> <%=rs.getString(1)%></p>  //<p>  <%  }  %>[code]  [/code]  please help
    Message was edited by:
    manu_am
    Message was edited by:
    manu_am

    I'm not an AWT expert, but here's my best guess to the problem...
    I'm not sure that the ActionListener is the correct event listener to use here.
    I don't think the straight TextArea throws action events, I could be wrong here I mainly have experience with swing.
    What event are you trying to react to here? Also is there any reason for not using Swing? Then you can use the JTextArea.
    Hope I'm of some help :)

  • Please explain what does this code does exactly

    Can any one explain me what does the below code does.
    This is the code written in one of the BADI (ME_PO_PRICING_CUST) .This badi will be triggered when a sales order delivery address is changed and while saving it this will be triggered. Over all what i come to know is they re trigerring a new version in this code. Can anyone explain me what exactly they are doing in this.Thanks...
    METHOD IF_EX_ME_PO_PRICING_CUST~PROCESS_KOMK.
      FIELD-SYMBOLS: <EKKO> TYPE ANY,
                     <PROCSTAT> TYPE MEPROCSTATE,
                     <FRGKE> TYPE FRGKE,
                     <YNAST> TYPE TABLE,
                     <WA_YNAST> TYPE NAST.
      IM_EKKO-PROCSTAT = 02.
    *break-point.
      ASSIGN ('(SAPLMEPO)EKKO') TO <EKKO>.
      ASSIGN ('(SAPLMEPO)YNAST[]') TO <YNAST>.
      IF <EKKO> IS ASSIGNED.
        ASSIGN COMPONENT 'PROCSTAT' OF STRUCTURE <EKKO> TO <PROCSTAT>.
        ASSIGN COMPONENT 'FRGKE' OF STRUCTURE <EKKO> TO <FRGKE>.
        IF <FRGKE> = 'R'.
          <PROCSTAT> = '02'.
        ENDIF.
      ENDIF.
      IF <YNAST> IS ASSIGNED.
        IF <FRGKE> = 'R'.
          LOOP AT <YNAST> ASSIGNING <WA_YNAST>.
            <WA_YNAST>-AKTIV = 'X'.
          ENDLOOP.
        ENDIF.
      ENDIF.
    ENDMETHOD.

    r_htkl must be a range table. check the declaration part of it.
    p_htkl is a parameter on selection screen i hope.
    so, there are four fields on a range table.(range table are similar to your select options)
    1. SIGN ( I or E  - Inclusive or Exculsive)
    2. OPTION(options like EQ = euqal, BT = Between, CP = contains pattern etc)
    3. LOW (value)
    4. HIGH (value)
    so..
    IF NOT p_htkl IS INITIAL. " checks if some thing is being passed to the parameter
    r_htkl-sign='I'. " give the sign a value I i.e it make inclusive sign
    r_htkl-option='EQ'. " EQ to option means you value will be checked for a equal to condition
    r_htkl-low=p_htkl. " the low field in now assigned the same value of the parameter p_hktl
    APPEND r_htkl. " the range table is appended.
    endif.
    so this range table can be used in select statements as :
    select * from abcd into gt where xyz in r_hktl. ==> this will check for a EQ condition with value in r_hktl-low in database or
    in if statements like : if abc in r_hktl. ==> this will check the EQ condition of abc with the r_hktl-low.
    Had it been
    r_htkl-sign='E'.
    then the condition is same but with a NOT.. that means NOT EQ or NOT BT etc.
    as exclusive of the option.
    etc.
    hope this is clear.
    AND PLEASE CLOSE THE OTHER THREAD (duplicate)

  • Please comment if this is a BUG in MII 12.2 or Normal?

    Hi,
    MII Version in Use:- 12.2.2 Build(235)
    I am trying to use "TransactionPath" function from Link editor to obtain the path for current transaction. Now when I execute this transaction from workbench, everything works fine as expected and desired.
    The problem comes when I run this transaction using Runner service.
    I mapped the result of TransactionPath function to an output variable and then checked its value using runner service, and the output was a blank tag(for my output variable). The bigger problem comes when I try to implement some string functionality on the output of TransactionPath function. At this the transaction fails becaue the links that hold string operation fails(and thats because TransactionPath is returning null value).
    Also, Just to proof check that my transaction, runner service URL and mappings etc are correct, I changed the TransactionPath function to TransactionId function and then I started getting result in my output variable tag in output xml. Thus with every refresh that I did , the transaction ID increased by 1 value.
    Please comment if this a known issue or bug or there is something that I am missing or this is a expected result for some reason !!
    Best Regards
    Piyush Govil

    Hi Piyush,
    I also checked that the transaction path is not coming in the output xml but from the workbench with a tracer it is working fine.
    I also verified that all other things are coming as they should but not the transaction path.
    Regards,
    Anuvrat

  • What is wrong in this code..please

    first of all,i kindly request team please not kill me by giving suggestion using xml parser.......can u please tell how this handle in reading follwing lines....
    orderREF="1036578"><edm:OrderItem><edm:Order orderID="1036579"/> ineed to retoeve value 1036578 i use following code
    final String START6_TAG="orderREF=";
    final String END6_TAG=">";
    final String END7_TAG="/>";
    as per my observation,the follwing code need not work
    if(line.indexOf(START6_TAG)> -1 ) {
    //this code handle "orderREF=" in stands for order id
    if(line.indexOf(END7_TAG,line.indexOf(START6_TAG))>-1){ //because if we use line.indexOf(END7_TAG)it take only first indexof that..
    efound9=false;
    asper above line this code cannot excecute.but igo to loop and set flag efound9=false, what is wrong in this code for handling
    orderREF="1036578"/><edm:OrderItem><edm:Order orderID="1036579"/> this type of line that also comes in same program,here also we need output as 1036578.please tell me what i will do to hanndle these

    first of all,i kindly request team please not kill
    me by giving suggestion using xml parser.......can u
    please tell how this handle in reading follwing
    lines.... I don't understand why you are so opposed to an xml parser. You could have spent 3 hours learning how to use it and been done with this problem in the time you've spent trying to hack your way around it.
    jdom tutorials: http://www.jdom.org/downloads/docs.html
    dom4j tutorials: http://www.dom4j.org/cookbook.html

Maybe you are looking for