Java servlet, DOM and xml help! please urgent!

I have to write a servlet that takes the user input to build a xml document using DOM API and should be able to append new entry to that xml file whenever any user adds an entry. I have written the fillowing code, can anyone please take a look at this code and tell me the right way to do it as this code is actually not creating any xml file and also in commented line of this code I tried by giving blank xml file name with just root element, so that this code can enter new elements like name, title as child element of the root, but doesn't work.
PrintWriter out = res.getWriter ();
res.setContentType ("text/html");
try
Document xmldoc = null;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
DOMImplementation impl = builder.getDOMImplementation();
// Document xmldoc = builder.parse(xmlfile name);
Element e = null;
Node n = null;
String name = req.getParameter("name");
String title = req.getParameter("title");
String address = req.getParameter("address");
xmldoc = impl.createDocument(null, "records", null);
Element root = xmldoc.getDocumentElement();
e = xmldoc.createElementNS(null, "name");
n = xmldoc.createTextNode(name);
e.appendChild(n);
root.appendChild(e);
e = xmldoc.createElementNS(null, "title");
n = xmldoc.createTextNode(title);
e.appendChild(n);
root.appendChild(e);
e = xmldoc.createElementNS(null, "address");
n = xmldoc.createTextNode(address);
e.appendChild(n);
root.appendChild(e);
DOMSource domSource = new DOMSource(xmldoc);
Source xslSource = new StreamSource (xsl file);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer(xslSource);
transformer.transform(domSource,new StreamResult (out));

Document xmldoc = null;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
xmldoc = documentBuilder.newDocument();
Element e = null;
Node n = null;
String name = req.getParameter("name");
String title = req.getParameter("title");
String address = req.getParameter("address");
e = xmldoc.createElement("name");
n = xmldoc.createTextNode(name);
e.appendChild(n);
xmldoc.appendChild(e);
e = xmldoc.createElement("title");
n = xmldoc.createTextNode(title);
e.appendChild(n);
xmldoc.appendChild(e);
e = xmldoc.createElement("address");
n = xmldoc.createTextNode(address);
e.appendChild(n);
xmldoc.appendChild(e);
DOMSource domSource = new DOMSource(xmldoc);
StreamSource xslSource = new StreamSource (xsl file);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer(xslSource);
transformer.transform(domSource,new StreamResult (out));

Similar Messages

  • AS2 and XML help please

    Hi, I found a previous post in this forum that does exactly
    what I would like to do, but since I am new to adobe flash I am
    missing some knowledge. I have the actionscript code and the xml
    file - what I need help with is the GUI. I open a new AS2 project
    and press F9 to insert the action code. What do I do next? Please
    help!
    I attach the previous actionscript code posted by another
    member.
    Best Regards Eva

    Hi, thanks for Your reply. Yes, I have the .xml file, what I
    need help with is the 'frame' that You display the picture in. Do I
    need to create a layer or scene? I guess that myContainer_mc in the
    code needs to be identified in this 'frame'. How do I go about
    doing this?
    Any help is most appriciated!
    Best Regards Eva

  • Help needed with Java 1.4 and xml Runtime problem

    I am working on a java 1.3 and JAXP1.1 written code. Now I want to compile and run it using J2SE 1.4. Here are the import statements from the existing code.
    import org.xml.sax.*;
    import org.xml.sax.helpers.DefaultHandler;
    import org.xml.sax.Locator;
    import javax.xml.parsers.SAXParser;
    import javax.xml.parsers.SAXParserFactory;
    import org.xml.sax.Attributes;
    import org.xml.sax.XMLReader;
    import org.xml.sax.InputSource;
    import java.sql.*;
    import java.net.*;
    import java.io.*;
    When I run the existing(using java 1.3 and Jaxp1.1) code I have to include the files crimson.jar and jaxp.jar in the windows 2000 CLASSPATH and works fine.
    But when I compile and run it using J2SE 1.4 which has the built in support for the saxp, I thought that I don't have to specify any CLASSPATH for the new 1.4 so I don't specify any Classpath and it gives me the Microsoft "ClassFactory cannot find the requested class" error which means that even thought the new java 1.4 has the xml classes as libraries yet it still requies some .jar files to be listed in the CLASSPATH.
    If I am right then what path will work(i.e what jar class I need to add to the CLASSPATH).
    Thanks for your help.
    RA.

    Thanks for your reply,
    I think I didn't specify when the error occurs. The ClassFactory related error occurs when I run the program, it compiles without any error.
    From what I understood somewhere in the java 1.4 docs, that the new 1.4 has the xml libraries built in by default so one doesn't need to give the classpaths just like we don't give any CLASSPATH for using swing and many of the other java packages. That is one thing.
    Second thing is that I also tried to use the java_xml_pack-spring02 and java_xml_pack-summer02; but non of them include the crimson.jar and the jaxp.jar files in them which are the 2 .jar files that makes the program run fine when used under the java 1.3 with combination of the jaxp1.1(which was downloaded seperately and then the CLASSPATH for it was set.).
    Can you please help what .jar files do I need to use instead. I tried to use the ones that the new java_xml_pack-spring02 and java_xml_pack-summer02 has for the jaxp in them.
    Thanks again.
    RA

  • VO Extension or Substitution Help Please - Urgent (iExpenses)

    Hi All,
    I am trying to limit the data of the Projects and Tasks LOV (on the ExpenseAllocationsPG) in iExpenses Module. I tried a VO substitution and failed with an error.
    ERROR: oracle.jbo.NoDefException: JBO-25002: Definition type View Definition not found
    basically it could not find my custom VO that i created, so i deleted it from the database.
    This is basically what i want to do:
    The standard Projects LOV from the ExpenseAllocationsPG
    1.oracle.apps.ap.oie.server.ProjectsLovVO
    SELECT * FROM (SELECT P.PROJECT_NUMBER PROJECT_NUMBER, P.PROJECT_NAME PROJECT_NAME, P.PROJECT_ID PROJECT_ID, P.START_DATE START_DATE, P.COMPLETION_DATE COMPLETION_DATE, (select O.NAME from HR_ALL_ORGANIZATION_UNITS O where P.CARRYING_OUT_ORGANIZATION_ID = O.ORGANIZATION_ID)PROJECT_ORGANIZATION_NAME FROM PA_PROJECTS_EXPEND_V P) QRSLT ORDER BY PROJECT_NUMBER
    2.oracle.apps.ap.oie.server.ProjectsVO
    SELECT * FROM (SELECT P.PROJECT_NUMBER PROJECT_NUMBER, P.PROJECT_NAME PROJECT_NAME, P.PROJECT_ID PROJECT_ID, P.START_DATE START_DATE, P.COMPLETION_DATE COMPLETION_DATE, O.NAME PROJECT_ORGANIZATION_NAME FROM PA_PROJECTS_EXPEND_V P, HR_ORGANIZATION_UNITS O WHERE P.CARRYING_OUT_ORGANIZATION_ID = O.ORGANIZATION_ID) QRSLT ORDER BY UPPER(PROJECT_NUMBER)
    I tried to do a substititution on both LOV's
    I then created custom Project LOV in a custom folder and i changed the the query a bit as follows to restrict the LOV to user projects:
    SELECT P.PROJECT_NUMBER PROJECT_NUMBER,
    P.PROJECT_NAME PROJECT_NAME ,
    P.PROJECT_ID PROJECT_ID ,
    P.START_DATE START_DATE ,
    P.COMPLETION_DATE COMPLETION_DATE ,
    (SELECT O.NAME
    FROM HR_ALL_ORGANIZATION_UNITS O
    WHERE P.CARRYING_OUT_ORGANIZATION_ID = O.ORGANIZATION_ID
    )PROJECT_ORGANIZATION_NAME
    FROM PA_PROJECTS_EXPEND_V P,
    PER_ASSIGNMENTS_F per,
    HR_ORGANIZATION_UNITS O,
    FND_USER fu
    WHERE per.person_id = pa_utils.getempidfromuser(fnd_global.user_id)
    AND per.primary_flag = 'Y'
    AND SYSDATE BETWEEN per.effective_start_date and per.effective_end_date
    AND p.project_id IN(select project_id from pa_transaction_controls
    where person_id = pa_utils.getempidfromuser(fnd_global.user_id)
    UNION ALL
    select project_id from pa_transaction_controls
    where person_id is null
    and expenditure_category = 'Labour'
    UNION ALL
    select project_id from pa_transaction_controls
    where person_id = pa_utils.getempidfromuser(fnd_global.user_id)
    and expenditure_category = 'Labour')
    AND p.carrying_out_organization_id = o.organization_id
    AND fu.employee_id = per.person_id
    **all that is in bold is what i added.
    my VO substitution does not work. i got errors.....
    Can someone please help me.....am i doin the right thing or is there another approach. It would greatly appreciated. I guess if i can get the Projects LOV to work then the Task Lov would be the same.
    Thanks
    Kresen

    hi Kresen,
    if u r unable to see that extended VO then verify wheter all these steps are done...
    after extending that VO in jdeveloper......Please FTP all the 3 (VO.xml, Voimpl and VORowImpl)
    into to $JAVA_TOP/<custom directory>/oracle/apps/ap/oie/server/ProjectsLovVO
    this thing looks very silly but important......
    Please Substitute the Seeded VO to the Extended VO in the Jdeveloper......then check in the .jpx file whether the substituion has taken place
    in .jpx file
    <Substitutes>
    <Substitute OldName ="oracle.apps.ap.oie.server.ProjectsLovVO" NewName ="xxxx.oracle.apps.ap.oie.server.ProjectsLovVO" />
    </Substitutes>
    this thing should be present....import that jpx file...
    Please convert the java files Voimpl and VorowImpl to Class files in the Server using javac command
    bounce the apache
    regards,
    sravanth

  • After effects and photoshop ,,,help please

    hi all
    can anybody help please.
    ive been making a short film with my son and putting some basic effects in, just for a laugh.
    i noticed an effect on ADOBE TV that was done by Gareth Edwards in his movie MONSTERS which i thought would be good to try out in my film but i carnt get it right,,
    here is the link to that effect...            http://tv.adobe.com/watch/customer-stories-video-film-and-audio/monsters/
    its the effect where he changes the menu board in a cafe to one of his infected area signs, he allso changes a few other signs.
    in the video he say that he exports a still frame from after effects into photoshop and puts on his image {with a few tweaks her and there}, when hes got it ok in photoshop ,it some how updates in after effects??
    can any please help ,thank you

    It's a simplified explanation of the process.  He left out explanations of motion tracking and perspective matching that were most certainly required for the shot being discussed.
    If you are doing the same process to a static, locked off shot, with no foreground objects passing in front of your sign, it would be very possible to create a single frame in Photoshop and just layer it over your scene in AE.  But once the camera moves, you will need to understand Motion Tracking.  If objects pass in front of the replaced component, you will need to understand Masking.

  • Mail and password: Help please!!!

    I have changed my password and on my iPhone and iPad there is no problem. However, on my iMac, 10.8.2 every time I put the computer to sleep and then wake it up again Mail tells me to verify my password. I press OK but it refuses to accept and I am forced to go to System Preferences, then mail where I press OK for the same password and the whole thing then works.
    In Yahoo it works perfectly!
    What is happening in Mail. I have deleted the account in preferences and set it up again but all to no avail.
    Help please!!!

    You might try the following steps:
    Restart the device by holding down the on/off button until the power down slider appears.
    Try entering your password in another location (i.e. when you are using a different wifi network)
    Reset all settings (settings > general > reset), this resets some of your settings to factory default. It’s not a complete removal of settings. It removes all of your preferences for Wi-Fi, Bluetooth, Do No Disturb, Notifications, General, Sounds, Brightness & Wallpaper and Privacy. It does not remove any of your data.
    Try signing out of iCloud and back in (only if find my phone is disabled)
    If this doesn’t help your best option may be to contact Apple ID Support, upon speaking to an operator you should explain that your problem is related to your Apple ID, this way you will not be charged for assistance, even if you don’t have an AppleCare plan.

  • Self teaching and need help please

    Hi, I'm trying to teach myself Java. Trying being the operative word. I've purchased the book "Java Software Solutions" and I'm trudging my way through it. Anyway, to my question: it's a 6 parter that was an test-yourself question in the book that I'm having a lot of trouble with. It says to use a program provided by Lewis and Loftus and edit that program so that it, 1. asks the user for a file name and when the user enters that on the keyboard it finds the file, 2. read each line and place it in a string array and setup an integer count variable to keep track of the lines read so it stops at the end, 3. Create an int array (of the size given by the count determined above) and filling it with the number part of each element of the String array. Create a String array (of the size given by the count determined above) and fill it with the name part of each element of the above String array, 4. Finish the implementation of the Sorts class to include the selectionSort method for arrays of Comparable. Include the isSorted method as a static boolean method that will take either an array of int or an array of Comparable, 5. Use the Sorts class to do both insertionSort and selectionSort on both arrays and refill the arrays between sorts and test the arrays before and after sorting with the isSorted method, 6. Give output consisting of the results of testing with the isSorted method before and after each sort on each array, the array names should be given, the count should be given.
    Many thanks to anyone who actually took the time to read this and many more to anyone who would help a struggling businessman trying to learn Java, if you could give me an example of this it would be much appreciated as this is the first place I've gotten stuck and could use an example to further my learning. The file that needs to be called is gcgc.dat and the Sorts program to be modified is this:
    //  Sorts.java       Author: Lewis and Loftus
    //  Demonstrates the selection sort and insertion sort algorithms,
    //  as well as a generic object sort.
    public class Sorts
       //  Sorts the specified array of integers using the selection
       //  sort algorithm.
       public static void selectionSort (int[] numbers)
          int min, temp;
          for (int index = 0; index < numbers.length-1; index++)
             min = index;
             for (int scan = index+1; scan < numbers.length; scan++)
                if (numbers[scan] < numbers[min])
                   min = scan;
             // Swap the values
             temp = numbers[min];
             numbers[min] = numbers[index];
             numbers[index] = temp;
       //  Sorts the specified array of integers using the insertion
       //  sort algorithm.
       public static void insertionSort (int[] numbers)
          for (int index = 1; index < numbers.length; index++)
             int key = numbers[index];
             int position = index;
             // shift larger values to the right
             while (position > 0 && numbers[position-1] > key)
                numbers[position] = numbers[position-1];
                position--;
             numbers[position] = key;
       //  Sorts the specified array of objects using the insertion
       //  sort algorithm.
       public static void insertionSort (Comparable[] objects)
          for (int index = 1; index < objects.length; index++)
             Comparable key = objects[index];
             int position = index;
             // shift larger values to the right
             while (position > 0 && objects[position-1].compareTo(key) > 0)
                objects[position] = objects[position-1];
                position--;
             objects[position] = key;
    }Again, many thanks to anyone who took the time to mull this over. Hope to hear from you soon.
    -Joe Williams

    Hi Joe,
    Whoa. What exactly are you asking here? Not to be mean, but this is the type of question goes unanswered in the forums. It looks too much like you're trying to get someone to do your work.
    My advice is, take it slow. Think about what you have read. Apply it to each step. Since you haven't given an indication of where you are in the book, I'm going to assume based on the problem that you're fairly far. I'm assuming you know how to compile and run a program, how to write a class, what inheritance is, etc.
    Step 1: How do you get input from the user? Has the book covered streams yet?
    Step 2: Again, do you understand what streams are and how to read from them?
    Step 3: Have you read about Wrappers and parsing strings?
    etc.
    Generally, in the forum, the kind of questions that get good responses are fairly specific, as in:
    "Hi, I tried this code:
    <code snippet />
    and I'm getting this error:
    <error />
    What could be wrong?"
    If you do that, you'll find this forum a great learning aid. But really, a lot of effort has to be put in before you bring it here.
    Good luck and keep learning! It will pay off.

  • My iPod touch has no sound from music and videos help please

    My iPod touch has no sound at all, help please guys.

    - The restore from backup
    - If still problem restore to factory defaults/new iPod.
    - Last, make an appointment at the Genius Bar of an Apple store.

  • HT5622 After installing iTunes Match I have lots most of my iTunes songs and albums help please

    After installing iTunes Match I have lost most of my songs and albums help?

    iTunes Match on the computer will not change the library content.  The iTunes Match 3 step process must complete on the computer based library before being associated with any IOS devices.
    It is always important to make a secure backup of your Song files prior to these activities.

  • Java and XML . PLEASE help

    Hi,
    I am using a SAX Parser to create XML documnets on the fly
    I am creating an xml document with some elements
    <name> userName </name>
    <pwd> pwd </pwd>
    Is there any class which can be used to create tag names
    like CreateTag("name") and endTag();
    which will create <name> </name>

    wouldn't be hard to write a method to do that:
    public String createTag(String tag) {
      StringBuffer buffer = new StringBuffer();
      buffer.append("<").append(name).append(">");
      return buffer.toString();
    }

  • Challenging issue for Java and XML Gurus.Please advise

    An extremely tricky and challenging code.
    I have been able to add 2 XML documents together
    using importNode().
    xmlDoc1
    <?xml version="1.0" encoding="UTF-8"?>
    <i:Interest xmlns:i="common">
    <i:Details xsi.type="i:vanilla.details.stock">
      <i:Strategy xsi.type="strategies:call">
         <strategies.Expiry>2009-12-01</strategies.Expiry>
      </i:Strategy>
    <i:Ref/>
    </i:Details>
    </i:Interest>
    xmlDoc2
    <?xml version="1.0" encoding="UTF-8"?>
    <i:Underlying value="KGF">
    <common:Currency>GBP</common:Currency>
    </i:Underlying>
    My Java Code to append them together
    NodeList list = xmlDoc2.getChildNodes();
    for (int i=0; i< list .getLength(); i++) {
         Element element = (Element)list.item(i);
         Node dup = xmlDoc1.importNode(element, true);
         xmlDoc1.getDocumentElement().appendChild(dup);
    Output:
    <?xml version="1.0" encoding="UTF-8"?>
    <i:Interest xmlns:i="common">
    <i:Details xsi.type="i:vanilla.details.stock">
         <strategies.Description>Call</strategies.Description>
         <strategies.Expiry>2009-12-01</strategies.Expiry>
       </i:Strategy>
    <i:Ref/>
    </i:Details>
    <i:Underlying value="KGF">
    <common:Currency>GBP</common:Currency>
    </i:Underlying>
    </i:Interest>     Query:
    I would like to add the 2nd XML Document after element <i:Ref> . How to do this? I dont want the 2nd XML doc after <i:details> but before it.
    Please help.

    Well. You say you want to insert a node as a child of another node, and it needs to be inserted before a certain other child node.
    There's an insertBefore() method in the Node interface. Use that.
    And if you thought that was a challenging issue then you might as well give up writing DOM code right now.

  • I'm new to java and need help please

    I have an assignment involves modifying a previous assignment. the code for the previous assigment is shown below.(it was required to be done as an applet this assigment can be an application or an applet) I'm trying to modify this code to read a text file (items.txt) that looks like this:
    item # description price(this line does not appear in the text file)
    001 shaving cream 400.00
    999 razors 30.00
    I need to load the item# and price from the text file into arrays(I have no clue how to use multi-dimensional arrays in java and would prefer not to)
    I need to search the arrays based on the values entered by the user (item # and quantity) calculate the total for that item then create a new text file which has each line item for that order in the form:
    item# quant price per item total(price per item*quant entered)
    also also I need to be able to display the four items listed above after each loop as well as all the previous item number and quantities they selected until they indicate they don't want to select anymore.
    I've been working on this for days and it seems like nothing I try works. My major problems are:
    1. I have no idea how to read the text file and load those 2 items into their respective arrays
    2. I can't seem to create a textfile that looks like text for the output file.
    code]
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.text.*;
    import java.util.Locale;
    public class arraySelection
    extends JApplet {
    //Initialize the applet
    private Container getContentPane=null;
    public void init() {
    String string_item, string_quantity;
    String output = "";
    String description= "";
    int counter= 0;
    int itemNumber= 0;
    double quantity = 0 ;
    double tax_rate=.07;
    double total= 0, price= 0;
    double tax, subtotal;
    double Pretotal= 0;
    double priceArray[] = {1, .5, 3.65, 0.02, 0.09};
    String descriptionArray[] = {"salt", "pepper", "paprika", "garlic", "thyme"};
    // create number format for currency in US dollar format
    NumberFormat moneyFormat = NumberFormat.getCurrencyInstance( Locale.US );
    //format to have the total with two digits precision
    DecimalFormat twoDigits = new DecimalFormat("0.00");
    //Jtextarea to display results
    JTextArea outputArea = new JTextArea ();
    // get applet's content pane
    Container container = getContentPane ();
    //attach output area to container
    container.add(outputArea);
    //set the first row of text for the output area
    output += "Invoice\nItem#\tDescription\tQuant@Price\t Line Total" + "\n";
    do //begin loop structure obtain input from user
    // obtain item number from user
    string_item = JOptionPane.showInputDialog(
    "Please enter an item number 1, 2, 3, 4, or 5:");
    //obtain quantity of each item that user enter
    string_quantity = JOptionPane.showInputDialog("Enter the quantity:");
    // convert numbers from type String to Integer or Double
    itemNumber = Integer.parseInt(string_item);
    quantity = Double.parseDouble(string_quantity);
    switch (itemNumber) {//Determine input from user to assign price and description
    case 10: // user input item =10
    price = priceArray[0];
    description = descriptionArray[0];
    break;
    case 20: // user input item =20
    price = priceArray [1];
    description = descriptionArray[1];
    break;
    case 30: //user input item =30
    price=priceArray[2];
    description = descriptionArray[2];
    break;
    case 40: //user input item =40
    price=priceArray[3];
    description = descriptionArray[3];
    break;
    case 50: //user input item =50
    price=priceArray[4];
    description = descriptionArray[4];
    break;
    default: // user input item is not on the list
    output += "Invalid value entered"+ "\n";
    price=0;
    description= "";
    //Calculates the total for each item number and stores it in subtotal
    subtotal = price * quantity;
    //display input from user
    output += itemNumber + "\t" + description + "\t\t"+ quantity + "@" +
    moneyFormat.format( price) + "\t" + moneyFormat.format( subtotal) + "\n";
    //accumulates the overall subtotal for all items
    Pretotal = Pretotal + subtotal;
    //verifies that the user wants to stop entering data
    string_item = JOptionPane.showInputDialog(" Enter a positive integer to continue or 0 to stop. ");
    itemNumber = Integer.parseInt(string_item);
    // loop termination condition if user's input is 0 .It will end the loop
    } while ( itemNumber!= 0);
    tax = Pretotal * tax_rate; // calculate tax amount
    total = Pretotal + tax; //calculate total = subtotal + tax
    //appends data regarding the subtotal, tax, and total to the output area
    output += "\n" + "Order Subtotal" + "\t" + moneyFormat.format( Pretotal) +
    "\n" + "Tax" + "\t\t" + twoDigits.format( tax ) + "\n" + "Order Total" +
    "\t\t" + moneyFormat.format( total );
    //attaches the data in the output variable to the output area
    outputArea.setText( output );
    } //end init
    }// end applet Invoice
    Any help or sugestions would be greatly appreaciated. I've been working on this for over a week and everything I try goes nowhere.

    item # description price(this
    line does not appear in the text file)
    001 shaving cream 400.00
    999 razors 30.00
    I need to load the item# and price from the text file
    into arrays(I have no clue how to use
    multi-dimensional arrays in java and would prefer not
    to)That's good, because you shouldn't use multidimensional arrays here. You should have a one-dimensional array (or java.util.List) of objects that encapsulate each line.
    I've been working on this for days and it seems like
    nothing I try works. My major problems are:
    1. I have no idea how to read the text file and load
    those 2 items into their respective arrays
    2. I can't seem to create a textfile that looks like
    text for the output file.The java.io package has file reading/writing classes.
    Here's a tutorial:
    http://java.sun.com/docs/books/tutorial/essential/io/index.html

  • I'm new to java and need help please(repost)

    I have an assignment involves modifying a previous assignment. the code for the previous assigment is shown below.(it was required to be done as an applet this assigment can be an application or an applet) I'm trying to modify this code to read a text file (items.txt) that looks like this:
    item # description price(this line does not appear in the text file)
    001 shaving cream 400.00
    999 razors 30.00
    I need to load the item# and price from the text file into arrays(I have no clue how to use multi-dimensional arrays in java and would prefer not to)
    I need to search the arrays based on the values entered by the user (item # and quantity) calculate the total for that item then create a new text file which has each line item for that order in the form:
    item# quant price per item total(price per item*quant entered)
    also also I need to be able to display the four items listed above after each loop as well as all the previous item number and quantities they selected until they indicate they don't want to select anymore.
    I've been working on this for days and it seems like nothing I try works. My major problems are:
    1. I have no idea how to read the text file and load those 2 items into their respective arrays
    2. I can't seem to create a textfile that looks like text for the output file.
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.text.*;
    import java.util.Locale;
    public class arraySelection
        extends JApplet {
      //Initialize the applet
      private Container getContentPane=null;
      public void init() {
           String string_item, string_quantity;
           String output = "";
           String description= "";
           int counter= 0;
           int itemNumber= 0;
           double quantity = 0 ;
           double tax_rate=.07;
           double total= 0, price= 0;
           double tax, subtotal;
           double Pretotal= 0;
           double priceArray[] = {1, .5, 3.65, 0.02, 0.09};
           String descriptionArray[] = {"salt", "pepper", "paprika", "garlic", "thyme"};
         // create number format for currency in US dollar format
         NumberFormat moneyFormat = NumberFormat.getCurrencyInstance( Locale.US );
         //format to have the total with two digits precision
         DecimalFormat twoDigits = new DecimalFormat("0.00");
         //Jtextarea to display results
         JTextArea outputArea = new JTextArea ();
         // get applet's content pane
          Container container = getContentPane ();
          //attach output area to container
          container.add(outputArea);
         //set the first row of text for the output area
        output +=  "Invoice\nItem#\tDescription\tQuant@Price\t Line Total" + "\n";
        do //begin loop structure obtain input from user
               // obtain item number from user
               string_item = JOptionPane.showInputDialog(
                   "Please enter an item number 1, 2, 3, 4, or 5:");
               //obtain quantity of each item that user enter
               string_quantity = JOptionPane.showInputDialog("Enter the quantity:");
               // convert numbers from type String to Integer or Double
               itemNumber = Integer.parseInt(string_item);
               quantity = Double.parseDouble(string_quantity);
                 switch (itemNumber) {//Determine input from user to assign price and description
                    case 10: // user input item =10
                      price = priceArray[0];
                      description = descriptionArray[0];
                      break;
                    case 20: // user input item =20
                      price = priceArray [1];
                      description = descriptionArray[1];
                      break;
                    case 30: //user input item =30
                      price=priceArray[2];
                      description = descriptionArray[2];
                      break;
                    case 40: //user input item =40
                      price=priceArray[3];
                      description = descriptionArray[3];
                      break;
                    case 50: //user input item =50
                      price=priceArray[4];
                      description = descriptionArray[4];
                      break;
                    default: // user input item is not on the list
                    output += "Invalid value entered"+ "\n";
                    price=0;
                    description= "";
             //Calculates the total for each item number and stores it in subtotal
             subtotal = price * quantity;
             //display input from user
             output += itemNumber + "\t" + description + "\t\t"+ quantity + "@" +
                       moneyFormat.format( price) + "\t" + moneyFormat.format( subtotal) + "\n";
             //accumulates the overall subtotal for all items
             Pretotal = Pretotal + subtotal;
            //verifies that the user wants to stop entering data
            string_item = JOptionPane.showInputDialog(" Enter a positive integer to continue or 0 to stop. ");
            itemNumber = Integer.parseInt(string_item);
          // loop termination condition if user's input is 0 .It will end the loop
       } while ( itemNumber!= 0);
        tax = Pretotal * tax_rate; // calculate tax amount
        total = Pretotal + tax; //calculate total = subtotal + tax
        //appends data regarding the subtotal, tax, and total to the output area
        output += "\n" + "Order Subtotal" + "\t" + moneyFormat.format( Pretotal) +
                  "\n" + "Tax" + "\t\t" + twoDigits.format( tax ) + "\n" + "Order Total" +
                  "\t\t" + moneyFormat.format( total );
         //attaches the data in the output variable to the output area
         outputArea.setText( output );
      } //end init
    }// end applet InvoiceAny help or sugestions would be greatly appreaciated. I've been working on this for over a week and everything I try goes nowhere.

    First answer: You shouldn't ask multiple questions in the same thread. Ask a specific question, with an appropriate subject line (optionally, assign the number of Dukes you are willing to give for the help). When question #1 is answered and question #2 arises, it's time for a new thread (don't forget to give out Dukes before moving on).
    Second answer: I think you need a Transfer Object (http://java.sun.com/blueprints/patterns/TransferObject.html). It's whole purpose is to hold/transfer instance data where it is needed. Create a class something like this:
    public class ItemTO
        private String _number;
        private String _description;
        private double _price;
        public ItemTO( String number, String description, double price )
            _number = number;
            _description = description;
            _price = price
        // Getter/Setter methods go here
    }then, in the code where you read in the file do something like this:
    BufferedReader input = null;
    try
        input  = new BufferedReader( new FileReader( "c:\\a.txt" ) );
        List items = new ArrayList();
        String line;
        String itemNumber;
        String itemDescription;
        double itemPrice;
        while ( (line  = input.readLine() ) != null )
         System.out.println( line );
            itemNumber = // Parse it from line
            itemDescription // Parse it from line
            itemPrice = // Parse it from line
            items.add( new ItemTO( itemNumber, itemDescription, itemPrice ) );
    catch ( FileNotFoundException fnfe )
        fnfe.printStackTrace();
    catch ( IOException ioe )
        ioe.printStackTrace();
    finally
        try
            if ( input != null )
                input.close();
        catch ( Exception e )
            e.printStackTrace();
    }As for how to parse the line of the file, I'll leave that to you for now. Are the three values delimited with any special characters?
    jbisotti

  • Java 1.4 and AES Algorithm PLEASE HELP!!

    I hope this question has not already been asked. I have spent a long time searching the archives and documentation.
    I am attempting to migrate from jsdk1.3 to jsdk1.4 but have come up against the following problem.
    I need to create keys and encrypt files and was doing it by using the following:
    import java.security.*;
    import cryptix.provider.key.RawKeyGenerator;
    import xjava.security.KeyGenerator;
    And in my code am using:
    SecureRandom rnd = new SecureRandom();
    rnd.nextInt();
    RawKeyGenerator kg = (RawKeyGenerator)KeyGenerator.getInstance("AES","Cryptix");
    kg.initialize(rnd, 32);
    key = kg.generateKey();
    But I now get the following exception.
    Unexpected exception in IJCE_SecuritySupport.registerTargets()
    Please report this as a bug to <[email protected]>, including
    any other messages displayed on the console, and a description of what appeared to cause the error.
    java.lang.InternalError: Unexpected exception in IJCE_SecuritySupport.registerTargets()
    at xjava.security.IJCE.reportBug(IJCE.java:701)
    at xjava.security.IJCE_SecuritySupport.<clinit>(IJCE_SecuritySupport.java:138)
    at xjava.security.IJCE.findTarget(IJCE.java:498)
    at xjava.security.IJCE.getProviderInternal(IJCE.java:666)
    at xjava.security.IJCE.getClassCandidate(IJCE.java:446)
    at xjava.security.IJCE.getImplementationClass(IJCE.java:410)
    at xjava.security.IJCE.getImplementation(IJCE.java:367)
    at xjava.security.KeyGenerator.getInstance(KeyGenerator.java:152)
    at uk.co.sundayta.docsys.KeyManager.createNewKey(KeyManager.java:96)
    at uk.co.sundayta.docsys.KeyManager.createEncodedKey(KeyManager.java:110)
    at uk.co.sundayta.docsys.KeyManager.createKey(KeyManager.java:71)
    at uk.co.sundayta.docsys.KeyManager.run(KeyManager.java:62)
    at java.lang.Thread.run(Thread.java:536)
    The KeyManager error at line 96 mentioned above is in my code and is related to the snipit of code mentioned above.
    I need 1.4 as I need to use the new 1.4 plug-in on the clients to unencrypt the data.
    I have not sent an email to the address mentioned above as I assume it is a migration problem.
    I also had a message saying:
    Netscape security model is no longer supported.
    Please migrate to the Java 2 security model instead.
    I cannot do this as I need the java 1.4 plug-in for something else on the client. If I compile with 1.3 and run with 1.4 there seems to be an incompatibility problem.
    I would be grateful for any advice as I need to ship this soon.
    Thanks Andrew Mercer.

    Hi!
    I was trying to run some examples from the JXTA platform with jdk_1.3 (the classic HelloWorld), and got a very similar exception. The problem is I'm quite a newbie with JXTA and have no idea whatsoever about security in java, so I don't know what to do about it. I got the same messages about migrate the security model and report the whole thing as a bug, and I actually tried to send the message, but the address doesn't exist, so I'm stuck. If you've come across a solution or someone who might help, I would really like to know it! I copy below the text for the exception, in case it's helpfull to you somehow.
    Kind regards,
    Marta
    Text for the exception:
    java.lang.NoSuchMethodError
         at xjava.security.IJCE_SecuritySupport.registerTargets(IJCE_SecuritySupport.java:155)
         at xjava.security.IJCE_SecuritySupport.<clinit>(IJCE_SecuritySupport.java:134)
         at xjava.security.IJCE.findTarget(IJCE.java:498)
         at xjava.security.IJCE.getProvidersInternal(IJCE.java:638)
         at xjava.security.IJCE.getClassCandidate(IJCE.java:426)
         at xjava.security.IJCE.getImplementationClass(IJCE.java:410)
         at xjava.security.IJCE.getImplementation(IJCE.java:367)
         at xjava.security.Cipher.getInstance(Cipher.java:485)
         at xjava.security.Cipher.getInstance(Cipher.java:452)
         at xjava.security.Cipher.getInstance(Cipher.java:395)
         at COM.claymoresystems.crypto.PEMData.writePEMObjectPEMData.java:154)
         at COM.claymoresystems.crypto.EAYEncryptedPrivateKey.writePrivateKey(EAYEncryptedPrivateKey.java:109)
         at net.jxta.impl.endpoint.tls.PeerCerts.appendPrivateKey(PeerCerts.java:174)
         at net.jxta.impl.endpoint.tls.PeerCerts.genPeerRootCert(PeerCerts.java:137)
         at net.jxta.impl.endpoint.tls.PeerCerts.generateCerts(PeerCerts.java:457)
         at net.jxta.impl.endpoint.tls.TlsConfig.init(TlsConfig.java:185)
         at net.jxta.impl.peergroup.Configurator.configureTls(Configurator.java:265)
         at net.jxta.impl.peergroup.Configurator.<init>(Configurator.java:202)
         at net.jxta.impl.peergroup.Platform.init(Platform.java:252)
         at net.jxta.peergroup.PeerGroupFactory.newPlatform(PeerGroupFactory.java:210)
         at net.jxta.peergroup.PeerGroupFactory.newNetPeerGroup(PeerGroupFactory.java:284)
         at SimpleJxtaApp.startJxta(SimpleJxtaApp.java:91)
         at SimpleJxtaApp.main(SimpleJxtaApp.java:73)
    Unexpected exception in IJCE_SecuritySupport.registerTargets()

  • HELP PLEASE urgent: Creating a package, and class that prints all...

    please help, 5 duke dollars up for the best answer, or first answer that solves my problem!
    Hello, I have created a package called molecule that contains classes named Water, Sugar, Carbon Dioxide, and SulfuricAcid, and a sub-package named molecule.atom. The atom sub-package contains classes named Carbon, Hydrogen, Oxygen, and Sulfur. Each class in the molecule package should re-define the toString() method to print the numbers and types of atoms that constitute the molecule. For example, molecule.Sugar.toString() should return the string:
    "Sugar: 6 Carbon, 12 Hydrogen, 6 Oxygen".
    So basically, I have created a folder in C:\molecule\ and a subfolder C:\molecule\atom\ . I have also created a class called ChemTest belonging to the default package. ChemTest.main() creates and prints instances of each molecule and atom, but does not contain any import statements. The problem is that the ChemTest.java file won't compile coming up with 16 errors!
    Can someone explain to me what I am doing wrong?
    here is one of the molecule classes, for example CarbonDioxide.java:
    package molecule;
    public class CarbonDioxide
         private String co2;
         public CarbonDioxide()
              co2 = "Carbon Dioxide: 1 Carbon, 2 Oxygen";
         public String toString()
              return co2;
    and here is one of the atom classes, for example Carbon.java:
    package molecule.atom;
    public class Carbon
         private String c;
         public Carbon()
              c = "Carbon: symbol = C, num = 6, weight = 12.011";
         public String toString()
              return c;
    now here is the ChemTest.java file that won't compile:
    public class ChemTest
         public static void main(String[]args)
              molecule.Water water = new molecule.Water();
              molecule.Sugar sugar = new molecule.Sugar();
              molecule.CarbonDioxide carbonDioxide = new molecule.CarbonDioxide();
              molecule.SulfuricAcid sulfuricAcid = new molecule.SulfuricAcid();
              molecule.atom.Carbon carbon = new molecule.atom.Carbon();
              molecule.atom.Oxygen oxygen = new molecule.atom.Oxygen();
              molecule.atom.Hydrogen hydrogen = new molecule.atom.Hydrogen();
              molecule.atom.Sulfur sulfur = new molecule.atom.Sulfur();
              System.out.println(water.toString());
              System.out.println(sugar.toString());
              System.out.println(carbonDioxide.toString());
              System.out.println(sulfuricAcid.toString());
              System.out.println();
              System.out.println(carbon.toString());
              System.out.println(oxygen.toString());
              System.out.println(hydrogen.toString());
              System.out.println(sulfur.toString());
    and finally, here are the errors:
    C:\molecule\ChemTest.java:5: cannot resolve symbol
    symbol : class Water
    location: package molecule
              molecule.Water water = new molecule.Water();
    ^
    C:\molecule\ChemTest.java:5: cannot resolve symbol
    symbol : class Water
    location: package molecule
              molecule.Water water = new molecule.Water();
    ^
    C:\molecule\ChemTest.java:6: cannot resolve symbol
    symbol : class Sugar
    location: package molecule
              molecule.Sugar sugar = new molecule.Sugar();
    ^
    C:\molecule\ChemTest.java:6: cannot resolve symbol
    symbol : class Sugar
    location: package molecule
              molecule.Sugar sugar = new molecule.Sugar();
    ^
    C:\molecule\ChemTest.java:7: cannot resolve symbol
    symbol : class CarbonDioxide
    location: package molecule
              molecule.CarbonDioxide carbonDioxide = new molecule.CarbonDioxide();
    ^
    C:\molecule\ChemTest.java:7: cannot resolve symbol
    symbol : class CarbonDioxide
    location: package molecule
              molecule.CarbonDioxide carbonDioxide = new molecule.CarbonDioxide();
    ^
    C:\molecule\ChemTest.java:8: cannot resolve symbol
    symbol : class SulfuricAcid
    location: package molecule
              molecule.SulfuricAcid sulfuricAcid = new molecule.SulfuricAcid();
    ^
    C:\molecule\ChemTest.java:8: cannot resolve symbol
    symbol : class SulfuricAcid
    location: package molecule
              molecule.SulfuricAcid sulfuricAcid = new molecule.SulfuricAcid();
    ^
    C:\molecule\ChemTest.java:10: cannot resolve symbol
    symbol : class Carbon
    location: package atom
              molecule.atom.Carbon carbon = new molecule.atom.Carbon();
    ^
    C:\molecule\ChemTest.java:10: cannot resolve symbol
    symbol : class Carbon
    location: package atom
              molecule.atom.Carbon carbon = new molecule.atom.Carbon();
    ^
    C:\molecule\ChemTest.java:11: cannot resolve symbol
    symbol : class Oxygen
    location: package atom
              molecule.atom.Oxygen oxygen = new molecule.atom.Oxygen();
    ^
    C:\molecule\ChemTest.java:11: cannot resolve symbol
    symbol : class Oxygen
    location: package atom
              molecule.atom.Oxygen oxygen = new molecule.atom.Oxygen();
    ^
    C:\molecule\ChemTest.java:12: cannot resolve symbol
    symbol : class Hydrogen
    location: package atom
              molecule.atom.Hydrogen hydrogen = new molecule.atom.Hydrogen();
    ^
    C:\molecule\ChemTest.java:12: cannot resolve symbol
    symbol : class Hydrogen
    location: package atom
              molecule.atom.Hydrogen hydrogen = new molecule.atom.Hydrogen();
    ^
    C:\molecule\ChemTest.java:13: cannot resolve symbol
    symbol : class Sulfur
    location: package atom
              molecule.atom.Sulfur sulfur = new molecule.atom.Sulfur();
    ^
    C:\molecule\ChemTest.java:13: cannot resolve symbol
    symbol : class Sulfur
    location: package atom
              molecule.atom.Sulfur sulfur = new molecule.atom.Sulfur();
    ^
    16 errors
    Please help!!!, thanks!

    HI,
    I tried your problem with the following directory structure:c:\java\ChemTest.java
    c:\java\molecule\CarbonDioxide.java
    c:\java\molecule\atom\Carbon.javaI set the dos-prompt to c:\java and ran the following commands:javac molecule\CarbonDioxide.java
    javac molecule\atom\Carbon.java
    javac -classpath . ChemTest.java- and it worked!
    Sure, in ChemTest.java I deleted all the lines refering to classes that you didn't post...
    I hope this helps you!
    Anja

Maybe you are looking for

  • How do I add my bank website to the list?

    How do I add my bank opening page on the bookmark list?

  • Problem in reading current user's mydocuments directory in Windows 2k/XP.

    Hi everybody! I'm reading some files from the current user's mydocuments. It is working fine with Windows 2K/XP english version. And my program is showing files and directories in right way. But when I run the same program on Windows 2K/XP polish lan

  • Convert XML to SAP internal table

    Hi gurus, My program is suppose to get current exchange rate file from website and upload it in SAP. by using FM 'HTTP_GET', im getting the data in XML format.My problem is..i have tried to use transformation but failed to map it against XML data ele

  • Component determination in BOM

    Hello, I have to include a procedure in a BOM component to determine if that component must be selected or not according to a caracteristic but the option is not enabled in the BOM item. Does anybody know if it is a customizing issue and if yer, wher

  • How To Migrate My Customized reports & Forms  To R12?

    Hi... How To Migrate My Customized reports & Forms To R12? I want to migrate my customized report&forms to R12 From 11.5.9 Base? how to find the customized Reports & Forms Location? How To Register the customized Reports & Forms? Regards **SBJ**