Help with JAVA StringObject - & assign user input; StringMethod

Hi Everyone! I need help with this Java Program, I need to write a program, single class, & file. That will prompt the user to enter a word. The output will be separted by hypens and do this until the user enters exit. I think this is done by using a string variable. Then use the length of the word to setup a loop to print each letter out with hypens. (example c-a-t)
1. I think I should store the word like this: Word.Method(). Not sure of this the API was confusing for me because I wasn't sure of what to do.
2. A string method to find out how many letters are in the user's word in order to setup a loop to print each letter out. I think I can use a While loop to accomplish this?
3. A string method to access each letter in a string object individually in order to print individual letters to the screen with those hypens. This is really confusing for me? Can this be accomplished in the While loop? or do I declare variables in the main method.
Any examples you can refer me to would be greatly appreciated. Thanks

Getting user input:
This may look strange to a newbie but there's nothing much you can do since you wanted a single class file:import java.io.*
public class InputTest {
   public static void main(String[] args) {
      BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
      System.out.println("Hi! Please type a word and press enter.");
      String lineReadFromUser = in.readLine();
      System.out.println("You typed " + lineReadFromUser);
}You can get the lenght of a String using the length() method. Example: int len = "Foobar".length();
You can get the individual characters of a String with the charAt() method. Example: char firstCharOfString = string.charAt(0);
(remember that the argument must be from 0 to length-1)
You can access the documentation of all classes, including java.lang.String, at http://java.sun.com/j2se/1.3/docs/api/index.html You can also download the docs.

Similar Messages

  • Need help with Java app for user input 5 numbers, remove dups, etc.

    I'm new to Java (only a few weeks under my belt) and struggling with an application. The project is to write an app that inputs 5 numbers between 10 and 100, not allowing duplicates, and displaying each correct number entered, using the smallest possible array to solve the problem. Output example:
    Please enter a number: 45
    Number stored.
    45
    Please enter a number: 54
    Number stored.
    45 54
    Please enter a number: 33
    Number stored.
    45 54 33
    etc.
    I've been working on this project for days, re-read the book chapter multiple times (unfortunately, the book doesn't have this type of problem as an example to steer you in the relatively general direction) and am proud that I've gotten this far. My problems are 1) I can only get one item number to input rather than a running list of the 5 values, 2) I can't figure out how to check for duplicate numbers. Any help is appreciated.
    My code is as follows:
    import java.util.Scanner; // program uses class Scanner
    public class Array
         public static void main( String args[] )
          // create Scanner to obtain input from command window
              Scanner input = new Scanner( System.in);
          // declare variables
             int array[] = new int[ 5 ]; // declare array named array
             int inputNumbers = 0; // numbers entered
          while( inputNumbers < array.length )
              // prompt for user to input a number
                System.out.print( "Please enter a number: " );
                      int numberInput = input.nextInt();
              // validate the input
                 if (numberInput >=10 && numberInput <=100)
                       System.out.println("Number stored.");
                     else
                       System.out.println("Invalid number.  Please enter a number within range.");
              // checks to see if this number already exists
                    boolean number = false;
              // display array values
              for ( int counter = 0; counter < array.length; counter++ )
                 array[ counter ] = numberInput;
              // display array values
                 System.out.printf( "%d\n", array[ inputNumbers ] );
                   // increment number of entered numbers
                inputNumbers++;
    } // end close Array

    Yikes, there is a much better way to go about this that is probably within what you have already learned, but since you are a student and this is how you started, let's just concentrate on fixing what you got.
    First, as already noted by another poster, your formatting is really bad. Formatting is really important because it makes the code much more readable for you and anyone who comes along to help you or use your code. And I second that posters comment that brackets should always be used, especially for beginner programmers. Unfortunately beginner programmers often get stuck thinking that less lines of code equals better program, this is not true; even though better programmers often use far less lines of code.
                             // validate the input
       if (numberInput >=10 && numberInput <=100)
              System.out.println("Number stored.");
      else
                   System.out.println("Invalid number.  Please enter a number within range."); Note the above as you have it.
                         // validate the input
                         if (numberInput >=10 && numberInput <=100)
                              System.out.println("Number stored.");
                         else
                              System.out.println("Invalid number.  Please enter a number within range."); Note how much more readable just correct indentation makes.
                         // validate the input
                         if (numberInput >=10 && numberInput <=100) {
                              System.out.println("Number stored.");
                         else {
                              System.out.println("Invalid number.  Please enter a number within range.");
                         } Note how it should be coded for a beginner coder.
    Now that it is readable, exam your code and think about what you are doing here. Do you really want to print "Number Stored" before you checked to ensure it is not a dupe? That could lead to some really confused and frustrated users, and since the main user of your program will be your teacher, that could be unhealthy for your GPA.
    Since I am not here to do your homework for you, I will just give you some advice, you only need one if statement to do this correctly, you must drop the else and fix the if. I tell you this, because as a former educator i know the first thing running through beginners minds in this situation is to just make the if statement empty, but this is a big no no and even if you do trick it into working your teacher will not be fooled nor impressed and again your GPA will suffer.
    As for the rest, you do need a for loop inside your while loop, but not where or how you have it. Inside the while loop the for loop should be used for checking for dupes, not for overwriting every entry in the array as you currently have it set up to do. And certainly not for printing every element of the array each time a new element is added as your comments lead me to suspect you were trying to do, that would get real annoying really fast again resulting in abuse of your GPA. Printing the array should be in its own for loop after the while loop, or even better in its own method.
    As for how to check for dupes, well, you obviously at least somewhat understand loops and if statements, thus you have all the tools needed, so where is the problem?
    JSG

  • Help with JTree data by user input

    I am trying to read data into a JTree without it being hardcoded.
    An example of the data is:
    String data[] = {"a","b","c",";","b","g","h",";","c","t",";","g","u"};
    The above data is taken from user input and stored in an array and checked for errors.
    I want to somehow read take the above array's data and put it into following format in some kind of loop but I am not sure how.
    Object[] hierarchy = {"a", new Object[]{"b",new Object[]{"g","u"},"h"},new Object[]{"c","t"}};
    This Object is then passed to a function that interpets it and prints out the appropriate JTREE structure. For the values above it would be:
    a
    ..b
    ....g
    ......l
    ......u
    ....h
    ..c
    ....t
    Tha problem is how to take the string array and put that data correctly into the Object array. I have been racking my feeble mind for quite sometime and if any one out there can see it or has a better idea of how to get my data into the JTree please let me know.
    Thanks

    //OutlookClient.java
    //uses also Console class from Bruce Eckel 
    //<applet code=OutlookClient width=500 height=300>
    //</applet>
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.event.*;
    import javax.swing.tree.*;
    import java.util.*;
    import javax.swing.UIManager;
    import javax.swing.SwingUtilities;
    import BruceEckel.*;
    import DynamicTree.*;
    import DynamicTreeNode.*;
    import java.lang.reflect.*;
    /* a class creating a dialog with the version, and other details about the program*/
    class AboutDialog extends JDialog {
         private JButton ok = null;
         private Container cp = null;
         private JTextField tname = null;
            public AboutDialog() {
                   //System.out.println("constructor");
                   ok = new JButton("OK");
                   cp = getContentPane();
                   cp.setLayout(new FlowLayout());
                   JLabel tlab = new JLabel("Outlook - client side");
                   cp.add(tlab);
                   //tname.setMinimumSize(new Dimension(50,10));
                   //tname.setSize(new Dimension(70,10));
                   tlab = new JLabel("Author: Jiri Machotka");
                   cp.add(tlab);
                   tlab = new JLabel("version 1.0 (September 2001)");
                   cp.add(tlab);
                   tlab = new JLabel("----------------------------------------------");
                   cp.add(tlab);
                   ok.addActionListener( new ActionListener() {
                      public void actionPerformed(ActionEvent e) {
                        dispose();
                      }//actionPerformed
                   });//addActionListener
                   cp.add(ok);
                   setSize(200,150);
                   setTitle("About the program");  
                   setModal(true);
         }//constructor
      *      <P>This class more-or-less contains a graphic design object used for interaction with a user.</P>
      *     Apart from all ScrollPanes, Buttons, and MenuItems, it contains also 3 interesting members:
      *     <ol>
      *     <li> <I>protected final DefaultMutableTreeNode topNode</I>, which is initialized with
      * a potent, non-removable object of the class <I>Node</I>
      *     <li> <I>protected final DefaultTreeModel treeModel</I>, which is initialized with the <I>topNode</I>
      *     <li> and finally <I>protected final DynamicTree dyn_tree</I>, which uses the 2 objects above
      *     </ol>
      *     <P> The <I>OutlookClient</I> is an applet, but it can be also processed as an application (thanks to
      *     a library by BruceEckel).</P>
    public class OutlookClient extends JApplet {
    //------------- properties -----------------------------------------
       private Action
            newMail = new AbstractAction ("New Mail", new ImageIcon("images/NewMailIcon.gif")){
              public void actionPerformed(ActionEvent e) {
                         txt.setText("NewMail");
         reply     = new AbstractAction ("Reply", new ImageIcon("images/ReplyIcon.gif")){
              public void actionPerformed(ActionEvent e) {
                         txt.setText("Reply");
       private JButton
         /*b1 = new JButton("Add a Node"),
         b2 = new JButton("Remove the current Node"),*/ //not used now
         tb1 = new JButton (newMail),
         tb2 = new JButton (reply);
       private JTextField
         txt = new JTextField(10);
       private Container
         leftArea = new Container(),
         rightArea = new Container();
       private JScrollPane
            left = new JScrollPane (leftArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS),
            right = new JScrollPane (rightArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
       private JSplitPane
            sp = new JSplitPane (JSplitPane.HORIZONTAL_SPLIT, left, right);
       private JToolBar
         toolBar = new JToolBar();
       private JMenuBar
         menuBar = new JMenuBar();
       /*ActionListener al = new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            String name = ( (JButton)e.getSource()).getText();
            txt.setText(name);
       };*/     //not used now - used as an action listener for buttons b1, b2
       private JMenu
         mainOutlookMenu = new JMenu ("Outlook activities"),
         othersMenu      = new JMenu ("Others"),
         mailMenu     = new JMenu ("Mails"),
         chatMenu     = new JMenu ("Chat"),
         look_and_feelMenu = new JMenu ("Look&Feel");
       private JMenuItem
         closeAppItem     = new JMenuItem ("Exit",KeyEvent.VK_F3),
         newMailItem     = new JMenuItem (newMail),
         replyItem     = new JMenuItem (reply);
       private JRadioButtonMenuItem
         windowsLookAndFeelItem;
       protected final DefaultMutableTreeNode topNode = new DefaultMutableTreeNode(new Node ("Outlook", false, true));
       protected final DefaultTreeModel treeModel = new DefaultTreeModel(topNode);
       protected final DynamicTree dyn_tree = new DynamicTree(topNode, treeModel);
    //-------------inner classes----------------------------------------
    /** <P>The class <I>MyRenderer</I> sets the renderer of the tree - by doing that icons can be assigned to
       * the tree's nodes. </P>
       * <P> It sould be probably a standard member of a class <I>DynamicTreeWithIcons</I>.</P>
       * <P> However, it uses the knowledge that the class <B>Node</B>, which is the only object that can be
       * found in the dynamic tree in this application, has a method <I>getIcon()</I>, which returns a
       * reference to the icon object assigned to the node.</P>
       * <P><B>This is the only place, where the class Node, or its methods are called explicitely.</B></P>
       protected class MyRenderer extends DefaultTreeCellRenderer {
         /** The constructor of the class.
           * - sets folders icons (opened, closed folder)
         public MyRenderer() {
                 //setLeafIcon(new ImageIcon("images/middle.gif")); //for leaves' icon, all at once!
              setOpenIcon(new ImageIcon("images/folder_open.gif"));
              setClosedIcon(new ImageIcon("images/folder_close.gif"));
         /** This overridden method gets the user-specified icon for leaf nodes. */
         public Component getTreeCellRendererComponent(
                   JTree tree,
                   Object value,
                   boolean sel,
                   boolean expanded,
                   boolean leaf,
                   int row,
                   boolean hasFocus) {
              super.getTreeCellRendererComponent(tree,value,sel,expanded,leaf,row,hasFocus);
              if (leaf) 
              //workaround: test if icon not eq. null
                     ImageIcon ic = getRightIcon(value);
                     if (ic == null) return this;
                     else
                          setIcon(ic);
              return this;
         }//overridden: getTreeCellRendererComponent
         private ImageIcon getRightIcon(Object value) {
           DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;
              try{
              Node node_object = (Node)(node.getUserObject());   
                 return (node_object.getIcon());
           catch (Exception e) { return null; }
         }// ImageIcon getRightIcon(Object value)
      }//class MyRenderer
    //-------------OutlookClient methods-----------------------------------------
       private void assignListeners(){
         dyn_tree.addTreeSelectionListener(new TreeSelectionListener() {
             public void valueChanged(TreeSelectionEvent e) {
              DefaultMutableTreeNode node = (DefaultMutableTreeNode)dyn_tree.getLastSelectedPathComponent();
              if (node == null) return;
              if (node.isLeaf()) { txt.setText(node.toString()); }
       }//assignListeners()
       private void createLayout(){
         leftArea.setLayout(new BoxLayout(leftArea,BoxLayout.Y_AXIS));
         rightArea.setLayout(new BoxLayout(rightArea,BoxLayout.Y_AXIS));
         //left.setMinimumSize(new Dimension(120,200));
         right.setMinimumSize(new Dimension(50,50));
         //rightArea.add(b1);
         //rightArea.add(b2);
         rightArea.add(txt);
         //leftArea.add(tree);  ... not nice (why?)
           left = new JScrollPane (dyn_tree, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);       
         left.setMinimumSize(new Dimension(180,200));
         sp.setLeftComponent(left);
       }//createLayout()
       private void createMenu(){
         ButtonGroup group = new ButtonGroup();
            JRadioButtonMenuItem rbMenuItem;
         closeAppItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F3, ActionEvent.ALT_MASK));
         closeAppItem.getAccessibleContext().setAccessibleDescription("Closes application");
         closeAppItem.addActionListener( new ActionListener() {
              public void actionPerformed(ActionEvent e) {System.exit(0);}
         othersMenu.setMnemonic(KeyEvent.VK_O);
         othersMenu.getAccessibleContext().setAccessibleDescription("System settings&Others");
            rbMenuItem = new JRadioButtonMenuItem("Java");
            rbMenuItem.setSelected(true);
            rbMenuItem.setMnemonic(KeyEvent.VK_J);
            group.add(rbMenuItem);
            rbMenuItem.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e) {setPLAF(UIManager.getCrossPlatformLookAndFeelClassName( ) );}
            look_and_feelMenu.add(rbMenuItem);
            rbMenuItem = new JRadioButtonMenuItem("Windows");
            rbMenuItem.setMnemonic(KeyEvent.VK_W);
            group.add(rbMenuItem);
            rbMenuItem.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e) {setPLAF("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");}
            look_and_feelMenu.add(rbMenuItem);
         windowsLookAndFeelItem = rbMenuItem;
         look_and_feelMenu.setMnemonic(KeyEvent.VK_L);
         look_and_feelMenu.getAccessibleContext().setAccessibleDescription("Look&Feel");
         JMenuItem aboutItem = new JMenuItem ("About");
         aboutItem.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                   AboutDialog ad = new AboutDialog();
                   ad.show();
         othersMenu.add(look_and_feelMenu);
         othersMenu.addSeparator();
         othersMenu.add(aboutItem);
         othersMenu.addSeparator();
         othersMenu.add(closeAppItem);
         mainOutlookMenu.setMnemonic(KeyEvent.VK_A);
         mainOutlookMenu.getAccessibleContext().setAccessibleDescription("Outlook activities");
         menuBar.add(mainOutlookMenu);
         menuBar.add(othersMenu);
         mailMenu.setMnemonic(KeyEvent.VK_M);
         mailMenu.getAccessibleContext().setAccessibleDescription("Mail activities");
         chatMenu.setMnemonic(KeyEvent.VK_C);
         chatMenu.getAccessibleContext().setAccessibleDescription("Chat");
         chatMenu.setEnabled(false);
         mainOutlookMenu.add(mailMenu);
         mainOutlookMenu.addSeparator();
         mainOutlookMenu.add(chatMenu);
         //mailMenu.add(newMail);
         //mailMenu.add(reply);     //class Action has problems to catch the accelerator keys
         newMailItem.setMnemonic(KeyEvent.VK_N);
         replyItem.setMnemonic(KeyEvent.VK_R);
         mailMenu.add(newMailItem);
         mailMenu.add(replyItem);
         newMailItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));
         replyItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, ActionEvent.ALT_MASK));
         //newMail.putValue(Action.NAME, "New mail");
         //newMail.putValue(Action.SHORT_DESCRIPTION, "New mail");
         //newMail.putValue(Action.LONG_DESCRIPTION, "New mail");
         //newMail.putValue(Action.MNEMONIC_KEY, "N");  //cast an exception. why?
         //newMail.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));     
         setJMenuBar(menuBar);
       }//createMenu()
       private void createToolBar(){
         //toolBar.add(newMail);
         //toolBar.add(reply);    //does not provide texts and mnemonics
         tb1.setMnemonic(KeyEvent.VK_N);
         tb2.setMnemonic(KeyEvent.VK_R);
         toolBar.add(tb1);
         toolBar.add(tb2);
       }//createToolBar()
       private void createNodes(DefaultMutableTreeNode topNode){
         //new for dynamic processing
         DefaultMutableTreeNode
              parentNode = null,
              leaveNode  = null;
         parentNode = dyn_tree.addObject(null,new Node ("MailFolders", false, true));
         dyn_tree.addObject(parentNode,new Node ("Inbox","images/InboxIcon.gif", false, false));
         dyn_tree.addObject(parentNode,new Node ("Outbox","images/OutboxIcon.gif", false, false));
         dyn_tree.addObject(parentNode,new Node ("Sent","images/SentIcon.gif", false, false));
         dyn_tree.addObject(parentNode,new Node ("Deleted","images/DeletedIcon.gif", false, false));
         //leaveNode.setEnabled(false);  //TODO: disable "Chat"node
         dyn_tree.addObject(null,new Node ("Chat", false, false));
       }//createcreateNodes(DefaultMutableTreeNode)
       private void setTreeSettings(){
         //one selection at one time
         dyn_tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
         //connect nodes with a thin line - Java style only
         dyn_tree.putClientProperty("JTree.lineStyle","Angled");
         //collapse the root's children first
         //tree.setShowsRootHandles(false);
         //icon adjustment
         MyRenderer MyRen = new MyRenderer();
         dyn_tree.setCellRenderer(MyRen);
         //modifiable tree - by double click - allows modifying of nodes' names
         // but unfortunately also restores original icons
         //tree.setEditable(true);
       }//setTreeSettings()
       private boolean setPLAF(String LookAndFeelName){
          try{
         UIManager.setLookAndFeel(LookAndFeelName);
         SwingUtilities.updateComponentTreeUI(this);
         return true;
          } catch (Exception e) {
         //e.printStackTrace(System.err);
         return false;
       }//setPLAF(String LookAndFeelName)
       private void trytosetLookAndFeel(){
          if (setPLAF("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"))
              windowsLookAndFeelItem.setSelected(true);
       }//trytosetLookAndFeel()
       /** The applet's <I>init()</I>.
         * Calls methods to construct all visible objects.
         * Apart from that it also assigns the renderer to the tree.
       public void init(){
         sp.setOneTouchExpandable(true);
            //sp.setDividerLocation(150); - system puts the value to optimize the left part
         sp.setPreferredSize(new Dimension(450,200));
         Container cp = getContentPane();
         cp.setLayout(new FlowLayout());
            createLayout();     
         createMenu();
         createToolBar();
         createNodes(topNode);
         setTreeSettings();
         //createPopupMenu();
         assignListeners();
         cp.add(toolBar);
         cp.add(sp);
         trytosetLookAndFeel();
       }//init()
       /** If called as an application.
         * The desired Windows Look&Feel is re-set again, when the applet is running. Otherwise, it in an application
         * it tends not to work correctly.
       public static void main(String[] args) {
         OutlookClient theApplet;
         BruceEckel.Console.run(theApplet=new OutlookClient(), 500, 300);
         theApplet.trytosetLookAndFeel();
       }//main(String[])
    }///:~Take a look namely at createNodes
    Hope it helps.

  • Need HELP with JTree created by user input

    I have been trying to create code that takes a user input string
    ex: a:b,c;b:g,h,j;g:k,m;b:u
    note: (the above string is then stored into a string array such in the format a:bc;b:ghj;g:km;b:u after it is verified that the hierarchy order is correct)
    The string is read in such that the any value before the : is a parent and its childern continue until a ; is found. Anyway verifying the sting I have accomplished and I have been able to input the string into a modified binary tree as long as there are only 2 childern per parent and graphically represents its structure of hierarchy. The problem is that each parent can have more the two childern.
    I have been working with the BTree class and find its output similar to what I am wanting which would represent a hierarchy of objects (files, employees, etc...) anyway I have been stumped as to how to get the above string into a format that can then create the correct JTree output without hard code.
    If any one has any suggestions on how to turn the data, in the string array into a usable format to create the correct JTree output, I would greatly appreciate it.
    In the above example the string array, a:bc;b:ghj;g:km;b:u would have a desired ouput of
    a
    ..b
    ....g
    ......k
    ......m
    ....h
    ....j
    ....u
    ..c
    Thanks
    Shane

    I have been trying to create code that takes a user input string
    ex: a:b,c;b:g,h,j;g:k,m;b:u
    note: (the above string is then stored into a string array such in the format a:bc;b:ghj;g:km;b:u after it is verified that the hierarchy order is correct)
    The string is read in such that the any value before the : is a parent and its childern continue until a ; is found. Anyway verifying the sting I have accomplished and I have been able to input the string into a modified binary tree as long as there are only 2 childern per parent and graphically represents its structure of hierarchy. The problem is that each parent can have more the two childern.
    I have been working with the BTree class and find its output similar to what I am wanting which would represent a hierarchy of objects (files, employees, etc...) anyway I have been stumped as to how to get the above string into a format that can then create the correct JTree output without hard code.
    If any one has any suggestions on how to turn the data, in the string array into a usable format to create the correct JTree output, I would greatly appreciate it.
    In the above example the string array, a:bc;b:ghj;g:km;b:u would have a desired ouput of
    a
    ..b
    ....g
    ......k
    ......m
    ....h
    ....j
    ....u
    ..c
    Thanks
    Shane

  • Help with java mapping

    PI File adapter has a processing option u2018Empty-Message Handlingu2019 to ignore or Write Empty Files. In case there is no data created after mapping on target side then this option determines whether to write an empty file or not. But there is a catch to this option when it comes to using it with File Content Conversion which is described in SAP Note u2018821267u2019. It states following:
    I configure the receiver channel with File content conversion mode and I set the 'Empty Message Handling' option to ignore. Input payload to the receiver channel is generated out of mapping and it does not have any record sets. However, this payload has a root element. Why does file receiver create empty output file with zero byte size in the target directory?  Example of such a payload generated from mapping is as follows:                                                           
    <?xml version="1.0" encoding="UTF-8"?>                          
    <ns1:test xmlns:ns1="http://abcd.com/ab"></ns1:test>
    solution :
    If the message payload is empty (i.e., zero bytes in size), then File adapter's empty message handling feature does NOT write files into the target directory. On the other hand, if the payload is a valid XML document (as shown in example) that is generated from mapping with just a root element in it, the File Adapter does not treat it as an empty message and accordingly it writes to the target directory. To achieve your objective of not writing files (that have just a single root element) into the target directory, following could be done:
    Using a Java or ABAP Mapping in order to restrict the creation of node itself during mapping. (This cannot be achieved via Message Mapping)
    Using standard adapter modules to do content conversion first and then write file. 
    can someone help with java mapping that can be used in this case?

    Hi,
        You have not mentioned the version of PI you are working in. In case you are working with PI 7.1 or above then here is the java mapping code you need to add after message mapping in the same interface mapping
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.Map;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;
    import org.w3c.dom.Document;
    import com.sap.aii.mapping.api.AbstractTransformation;
    import com.sap.aii.mapping.api.StreamTransformationException;
    import com.sap.aii.mapping.api.TransformationInput;
    import com.sap.aii.mapping.api.TransformationOutput;
    public class RemoveRootNode extends AbstractTransformation{
         public void execute(InputStream in, OutputStream out)
         throws StreamTransformationException {
    // TODO Auto-generated method stub
    try
         DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
         DocumentBuilder builderel=factory.newDocumentBuilder();
         /*input document in form of XML*/
         Document docIn=builderel.parse(in);
         /*document after parsing*/
         Document docOut=builderel.newDocument();
         TransformerFactory tf=TransformerFactory.newInstance();
         Transformer transform=tf.newTransformer();
         if(docIn.getDocumentElement().hasChildNodes())
              docOut.appendChild(docOut.importNode(docIn.getDocumentElement(),true));
              transform.transform(new DOMSource(docOut), new StreamResult(out));
         else
              out.write(null);
    catch(Exception e)
    public void setParameter(Map arg0) {
    // TODO Auto-generated method stub
    public static void main(String[] args) {
    // TODO Auto-generated method stub
    try{
         RemoveRootNode genFormat=new RemoveRootNode();
         FileInputStream in=new FileInputStream("C:\\apps\\sdn\\rootNode.xml");
         FileOutputStream out=new FileOutputStream("C:\\apps\\sdn\\rootNode1.xml");
         genFormat.execute(in,out);
         catch(Exception e)
         e.printStackTrace();
    public void transform(TransformationInput arg0, TransformationOutput arg1)
              throws StreamTransformationException {
         // TODO Auto-generated method stub
         this.execute(arg0.getInputPayload().getInputStream(), arg1.getOutputPayload().getOutputStream());
    In case you are working in PI 7.0 you can use this code
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.Map;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;
    import org.w3c.dom.Document;
    import com.sap.aii.mapping.api.StreamTransformation;
    import com.sap.aii.mapping.api.StreamTransformationException;
    public class RemoveRootNode implements StreamTransformation{
         public void execute(InputStream in, OutputStream out)
         throws StreamTransformationException {
    // TODO Auto-generated method stub
    try
         DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
         DocumentBuilder builderel=factory.newDocumentBuilder();
         /*input document in form of XML*/
         Document docIn=builderel.parse(in);
         /*document after parsing*/
         Document docOut=builderel.newDocument();
         TransformerFactory tf=TransformerFactory.newInstance();
         Transformer transform=tf.newTransformer();
         if(docIn.getDocumentElement().hasChildNodes())
              docOut.appendChild(docOut.importNode(docIn.getDocumentElement(),true));
              transform.transform(new DOMSource(docOut), new StreamResult(out));
         else
              out.write(null);
    catch(Exception e)
    public void setParameter(Map arg0) {
    // TODO Auto-generated method stub
    public static void main(String[] args) {
    // TODO Auto-generated method stub
    try{
         RemoveRootNode genFormat=new RemoveRootNode();
         FileInputStream in=new FileInputStream("C:\\apps\\sdn\\rootNode.xml");
         FileOutputStream out=new FileOutputStream("C:\\apps\\sdn\\rootNode1.xml");
         genFormat.execute(in,out);
         catch(Exception e)
         e.printStackTrace();
    The code for PI 7.0 should also work for PI 7.1 provided you use the right jar files for compilation, but vice-versa is not true.
    Could you please let us know if this code was useful to you or not?
    Regards
    Anupam
    Edited by: anupamsap on Dec 15, 2011 9:43 AM

  • Help With Java Alarm

    Hello Everybody
    I Want To Make an Alarm Application With Java Like
    The User Enters Alarm Time as 3.15.4 AM or something like that
    which class shall i use?
    if there's any demos that would be great.
    Thank You

    Another Question
    In The following Code Sir I Want The User to input The Time In The Format h/m/s/am.pm
    And After That Specific Time Passes an action happens
    How to Do that?
    import java.awt.*;
    import javax.swing.*;
    import java.text.DateFormat;
    import java.util.Date;
    public class Alarm extends Thread {
        public static void main(String[] args) {
             final JLabel label=new JLabel();
             JButton button=new JButton("Set Alarm");
             JTextArea tarea=new JTextArea("Enter Task Here",4,21);
             JScrollPane scroll=new JScrollPane(tarea);
             JTextField text1=new JTextField("hh",2);
             JTextField text2=new JTextField("mm",2);
             JTextField text3=new JTextField("ss",2);
             JTextField text4=new JTextField("AM/PM",4);
             text1.setToolTipText("Hours From 1 To 12");
             text2.setToolTipText("Minutes From 0 To 60");
             text3.setToolTipText("Seconds From 0 To 60");            
             JFrame frame=new JFrame("JAlarm");
             frame.setSize(270,180);
             JPanel panel1=new JPanel();
             panel1.add(label);
             panel1.add(scroll);
               Thread t = new Thread() {
            public void run() {
                 for(;;){
                  Date now = new Date();
                 label.setText(DateFormat.getTimeInstance().format(now));
        t.start();
             JPanel panel2=new JPanel();
             panel2.add(button);
             panel2.add(text1);
             panel2.add(text2);
             panel2.add(text3);
             panel2.add(text4);
             frame.setLayout(new BorderLayout());
             frame.add(panel1,BorderLayout.NORTH);
             frame.add(panel2,BorderLayout.CENTER);
             frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             frame.setVisible(true);               
    }

  • Newbie help with java :(

    Hey guys bare with me as this is my first assignment for my Java class. Here is the assignement and my class must be named payroll1. Any help on correcting or pointing out what is wrong with my code would be great.
    Create a non-GUI based Java application that calculates weekly pay for an
    employee. The application should display text that requests the user input the name of the employee, the hourly rate, and the number of hours worked for that week. The application should then print out the name of the employee and the weekly pay amount. In the printout, display the dollar symbol ($) to the left of the weekly pay amount and format the weekly pay amount to display currency.
    // Payroll1.java
    // Payroll1 that displays calculates weekly pay for an employee
    import java.util.Scanner; // program uses class payroll1
    import java.text.NumberFormat; // program uses class NumberFormat
    public class Payroll1 {
    // main method begins execution of Java application
    public static void main(String[] args) {
    // create payroll1 to obtain input from command window
    payroll1 input = new payroll1( System.in );
    NumberFormat currency = new DecimalFormat("\u00A4 #.00");
    String fname; // first name to be entered
    String lname; // last name to be entered
    double hourly; // hourly rate to be entered
    int hours; // number of hours worked to be entered
    double product; // product of hourly and hours
    System.out.print( " Enter the employee's first name: "); // prompt for name
    fname = input.nextLine(); // read first name from user
    System.out.print( " Enter the employee's last name: "); // prompt for name
    lname = input.nextLine(); // read last name from user
    System.out.print( " Enter the hourly rate."); // prompt for hourly rate
    hourly = input.nextDouble(); //read hourly rate from user
    System.out.print( " Enter the number of hours worked for the week."); // prompt for hours
    hours = input.nextInt(); //read number of hours worked
    product = hourly * hours; // multiply numbers
    System.out.println("Employee Name is: " + fname + " " + lname);
    System.out.println("Hourly wage is: " + hourly);
    System.out.println("Weekly pay is: " + currency.format(product));
    } // end method main
    } // end class Payroll1
    Here are the errors I receive when I run the program in RealJ
    C:\IT215\payroll 1\payroll1.java:6: class Payroll1 is public, should be declared in a file named Payroll1.java
    public class Payroll1 {
    ^
    .\payroll1.java:6: class Payroll1 is public, should be declared in a file named Payroll1.java
    public class Payroll1 {
    ^
    C:\IT215\payroll 1\payroll1.java:12: cannot access payroll1
    bad class file: .\payroll1.java
    file does not contain class payroll1
    Please remove or make sure it appears in the correct subdirectory of the classpath.
    payroll1 input = new payroll1( System.in );
    ^
    3 errors
    Exit code: 1
    There were errors

    Are you using J2SDK 1.5.0 beta 1 or J2SDK 1.4.2? Are you using the docs from 1.5 and the compiler from 1.4.2?
    private java.util.ArrayList jobsList=new java.util.ArrayList(100); //-- 1.4.2 code
    private java.util.List<Job> jobsList = new java.util.ArrayList<Job> (100); //-- 1.5.0 code (preferred style)
    private java.util.ArrayList<Job> jobsList = new java.util.ArrayList<Job> (100); //-- 1.5.0 codeAs a matter of style, use the interface and not the real class when declaring a variable like the jobsList above whenever possible or applicable.
    You do not need to cast the object newJob to Object. And you have inverted the positions of the parameters.
    void add(int index, E element)
    Inserts the specified element at the specified position in this list (optional operation).
    jobsList.add(Index, newJob);

  • Need help with Java, have a few questions about my Applet

    Purpose of the program: To create a mortgage calculator that will allow the user to input the loan principal then select 1 of 3 choices from a combo-box (7 years @ 5.35%, 15 years @ 5.50%, 30 years @ 5.75%).
    Problem: My program was working properly (so I thought). I can get the program to properly compile and run through TextPad. However, I noticed that when the user clicks the calculate more than once (with the same input), it slightly alters the output calculations. So that is my first question, Why is it doing that?  How can I get it only calculate that information once unless the user changes it etc?
    My next question is regarding my exit button. I was told by my instructor (who has already stated he won't help any of us) that my exit button does not work for an applet and only for an application. So, how can I create an exit button that will work with an applet? I thought I did it right but I can't find any resources online for this.
    Next question, why isn't my program properly validating invalid input? My program should only allow numeric input and nothing more.
    And last question, when invalid input is entered and the user clicks calculate, why isn't my JOptionPane window for error messages not displaying?
    I know my code is a little long so I have to post this in two messages. Please don't criticize me for what I am doing, that is why I am learning and have come to this forum for help. Thanks
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.*;
    import java.text.NumberFormat;
    import java.text.DecimalFormat;
    // Creating the main class
    public class test extends JApplet implements ActionListener
         // Defining of format information
         JLabel heading = new JLabel("McBride Financial Services Mortgage Calculator");
         Font newFontOne = new Font("TimesRoman", Font.BOLD, 20);
         Font newFontTwo = new Font("TimesRoman", Font.ITALIC, 16);
         Font newFontThree = new Font("TimesRoman", Font.BOLD, 16);
         Font newFontFour = new Font("TimesRoman", Font.BOLD, 14);
         JButton calculate = new JButton("Calculate");
         JButton exitButton = new JButton("Quit");
         JButton clearButton = new JButton("Clear");
         JLabel instructions = new JLabel("Please Enter the Principal Amount Below");
         JLabel instructions2 = new JLabel("and Select a Loan Type from the Menu");
         // Declaration of variables
         private double principalAmount;
         private JLabel principalLabel = new JLabel("Principal Amount");
         private NumberFormat principalFormat;
         private JTextField enterPrincipal = new JTextField(10);
         private double finalPayment;
         private JLabel monthlyPaymentLabel = new JLabel("  Monthly Payment    \t         Interest Paid    \t \t            Loan Balance");
         private NumberFormat finalPaymentFormat;
         private JTextField displayMonthlyPayment = new JTextField(10);
         private JTextField displayInterestPaid = new JTextField(10);
         private JTextField displayBalance = new JTextField(10);
         // Creation of the String of arrays for the ComboBox
         String [] list = {"7 Years @ 5.35%", "15 Years @ 5.50%", "30 Years @ 5.75%"};
         JComboBox selections = new JComboBox(list);
         // Creation of the textArea that will display the output
         private TextArea txtArea = new TextArea(5, 10);
         StringBuffer buff = null;
              Edited by: LoveMyAJ on Jan 19, 2009 1:49 AM

    // Initializing the interface
         public void init()
              // Creation of the panel design and fonts
              JPanel upper = new JPanel(new BorderLayout());
              JPanel middle = new JPanel(new BorderLayout());
              JPanel lower = new JPanel(new BorderLayout());
              JPanel areaOne = new JPanel(new BorderLayout());
              JPanel areaTwo = new JPanel(new BorderLayout());
              JPanel areaThree = new JPanel(new BorderLayout());
              JPanel areaFour = new JPanel(new BorderLayout());
              JPanel areaFive = new JPanel(new BorderLayout());
              JPanel areaSix = new JPanel(new BorderLayout());
              Container con = getContentPane();
              getContentPane().add(upper, BorderLayout.NORTH);
              getContentPane().add(middle, BorderLayout.CENTER);
              getContentPane().add(lower, BorderLayout.SOUTH);
              upper.add(areaOne, BorderLayout.NORTH);
              middle.add(areaTwo, BorderLayout.NORTH);
              middle.add(areaThree, BorderLayout.CENTER);
              middle.add(areaFour, BorderLayout.SOUTH);
              lower.add(areaFive, BorderLayout.NORTH);
              lower.add(areaSix, BorderLayout.SOUTH);
              heading.setFont(newFontOne);
              instructions.setFont(newFontTwo);
              instructions2.setFont(newFontTwo);
              principalLabel.setFont(newFontThree);
              monthlyPaymentLabel.setFont(newFontFour);
              displayInterestPaid.setFont(newFontFour);
              displayBalance.setFont(newFontFour);
              areaOne.add(heading, BorderLayout.NORTH);
              areaOne.add(instructions, BorderLayout.CENTER);
              areaOne.add(instructions2, BorderLayout.SOUTH);
              areaTwo.add(principalLabel, BorderLayout.WEST);
              areaTwo.add(enterPrincipal, BorderLayout.EAST);
              areaThree.add(selections, BorderLayout.NORTH);
              areaFour.add(calculate, BorderLayout.CENTER);
              areaFour.add(exitButton, BorderLayout.EAST);
              areaFour.add(clearButton, BorderLayout.WEST);
              areaFive.add(monthlyPaymentLabel, BorderLayout.CENTER);
              areaSix.add(txtArea, BorderLayout.CENTER);
              // Using the ActionListener to determine when each button is clicked
              calculate.addActionListener(this);
              exitButton.addActionListener(this);
              clearButton.addActionListener(this);
              enterPrincipal.requestFocus();
              selections.addActionListener(this);
         // The method that will perform specific actions defined below
         public void actionPerformed(ActionEvent e)
              Object source = e.getSource();
              buff = new StringBuffer();
              // Outcome of pressing the calculate button
              if (source == calculate)
                   // Used to call upon the user chosen selection
                   int selection = selections.getSelectedIndex();
                   // If statement to call upon Loan One's Method
                   if (selection == 0)
                        Double data = (Double)calculateLoanOne();
                        String sourceInput = data.toString();
                        displayMonthlyPayment.setText(sourceInput);
                        txtArea.setText(buff.toString());
                   // If statement to call upon Loan Two's Method
                   else if (selection == 1)
                        Double data = (Double)calculateLoanTwo();
                        String sourceInput = data.toString();
                        displayMonthlyPayment.setText(sourceInput);
                        txtArea.setText(buff.toString());
                   // If statement to call upon Loan Three's Method
                   else if (selection == 2)
                        Double data = (Double)calculateLoanThree();
                        String sourceInput = data.toString();
                        displayMonthlyPayment.setText(sourceInput);
                        txtArea.setText(buff.toString());
                   // Outcome of pressing the clear button
                   else if (source == clearButton)
                        enterPrincipal.setText("");
                        displayMonthlyPayment.setText("");
                        selections.setSelectedIndex(0);
                        txtArea.setText("");
                   // Outcome of pressing the quit button
                   else if (source == exitButton)
                        System.exit(1);
         // Method used to validate user input
         private static boolean validate(JTextField in)
              String inText = in.getText();
              char[] charInput = inText.toCharArray();
              for(int i = 0; i < charInput.length; i++)
                   int asciiVal = (int)charInput;
              if((asciiVal >= 48 && asciiVal <= 57) || asciiVal == 46)
              else
                   JOptionPane.showMessageDialog(null, "Invalid Character, Please Use Numeric Values Only");
                   return false;
                   return true;

  • Help with Java Web Service

    Hi,
    I tried integrating java code with java embedding acitivity, but in em it is failing. Can anybody know how to convert the below java code to a webservice, so that I can pass the input paramaters directly to that webservice. I tried of converting java code to webservice in jdeveloper, but because of static void main it is not converting. Can somebody help me in this issue.
    this is the original executable java code.
    package com.holx.api.test;
    import java.util.HashMap;
    import com.agile.api.APIException;
    import com.agile.api.AgileSessionFactory;
    import com.agile.api.IAdmin;
    import com.agile.api.IAgileClass;
    import com.agile.api.IAgileList;
    import com.agile.api.IAgileSession;
    import com.agile.api.IAutoNumber;
    import com.agile.api.IDataObject;
    import com.agile.api.INode;
    import com.agile.api.IProperty;
    import com.agile.api.IServiceRequest;
    import com.agile.api.PropertyConstants;
    import com.agile.api.ServiceRequestConstants;
    import com.agile.px.ActionResult;
    import java.net.URL;
    public class TestAgileAPI {
    //     @Override
    //     public ActionResult doAction(IAgileSession arg0, INode arg1,
    //               IDataObject arg2) {
              // TODO Auto-generated method stub
    //          return null;
         * @param args
         public static void main(String[] args) {
              IAgileSession m_session = null;
              IAdmin admin = null;
              IAgileClass cls = null;
         String sr="PR-KB00028";
    String userName="*******";
    String password="*******";
    String URL="*********";
              try {
                   HashMap params = new HashMap();
                   params.put(AgileSessionFactory.USERNAME, userName);
                   params.put(AgileSessionFactory.PASSWORD, password);
                   AgileSessionFactory instance = AgileSessionFactory.getInstance(URL);     
                   m_session = instance.createSession(params);     
                   admin = m_session.getAdminInstance();
                   cls = admin.getAgileClass( "ProblemReport" );
                   IServiceRequest psr = (IServiceRequest)m_session.createObject( "ProblemReport", sr);
              psr.setValue(ServiceRequestConstants.ATT_COVER_PAGE_DESCRIPTION, "KB-Test-20121400");
              } catch (APIException e) {
                   e.printStackTrace();
              } finally {
                   m_session.close();
    Can somebody help me in converting this code into a webservice which accepts String SR as input from soa.
    Thanks,

    Hi Francois,
    I never tried to use a webservice in the value help wizzard, so I don't know if it works or not.
    But for your problem you can build your own value help to avoid the problem.
    You told us that the webservice works in the storyboard. The value help wizard "only" creates a popup iView in your model and assigns the output field of the popup to an input field in a form.
    Maybe as a solution you can insert a popup to the model by yourself. Assign the output field of your popup to the input field for which you want to have the value help. Inside the popup iView you can use your custom built webservice.
    I know that this is a little bit circuitous, but I think it will work.
    Regards
    Christophe

  • Need help with java will even pay

    I need extreme help. I just don't have time lately to write these programs and I have fallen extremely behind. Basically all I need is to pass this class and right now until I can get some more help I just can't make the deadlines. If someone could help me I will pay you just like a tutor.
    Requirements for Lab.
    You will need to develop a variety of classes for this lab. Specifically, you need to create:
    +1. a "PersonGUI" class that displays fields for a person's: firstName, lastName, identificationNum, and sex.+
    +2. a "StudentGUI" class that provides Java components for the entry of: classification (freshman, sophomore, junior, senior, or graduate student), and Checkboxes for (a student being in the Honor's program and/or in the ROTC).+
    +3. a "FacultyGUI" class that provides Java components for the entry of: rank (instructor, assistant, associate, or full professor), years of service, and salary.+
    +4. a "Statistics" class that, when instantiated, creates an object containing an instance variable for each of the the statistical values outlined below. (Each of these instance variables should be declared to be "private".)+
    Your main Lab6 class should provide a means for the user to:
    +1. Specify the kind of personal data to be entered (Student or Faculty), and+
    +2. Then, depending on the choice made, appropriate fields should be displayed to allow the user to input appropriate information for the type of personal data being entered, and+
    +3. Controls that support the following functionality:+
    * a "CANCEL" control that will terminate any operation currently being performed and return the user to the "Startup" window.
    * a "SAVE" control that will cause the just entered data to be harvested from the graphical user interface and the appropriate statistics to be updated. Note: this function may NOT be performed if any of the student or faculty member data fields have not been filled in.
    * a "RESET" control that will erase all information recorded to date (i.e., all summary variables are reset to zero).
    * a "CLEAR" control that will erase all fields for the personal data currently being entered.
    * and a "DISPLAY TOTALS" control that will display, when pressed, the following data:
    +1. For students:+
    +1. total number of students entered so far,+
    +2. number who are male and number who are female,+
    +3. number of freshmen, sophomores, juniors, seniors, and graduate students,+
    +4. number of students who are in the Honor's program and number who are in the ROTC.+
    +2. For faculty:+
    +1. total number of faculty entered so far,+
    +2. number who are male and number who are female,+
    +3. the name and salary of the highest paid faculty member on campus.+
    Your program should validate numeric data to the extent:
    +1. no numeric field (id number, years of service, or salary) may be left blank by the user. If done so, the user should be alerted to enter a numeric value.+
    +2. when the user enters a "years of service" value for a faculty member - the value entered should be verified to be a valid integer value in the range 1 to 50. If the data entered is outside the valid range or is not a valid integer - your program should reject the value and prompt the user that invalid data has been entered and that a new value is necessary.+
    +3. when a faculty salary is entered, verify that it is a floating-point value in the range $35,000 to $200,000. Handle invalid data as described above.+
    +4. Similarly, if an invalid integer value is entered for the identification number, the value should be rejected and the user prompted to reenter.+
    +5. Information should not be saved, nor should statistical values be updated, until all numeric data has been validated.+
    Note -- You will be graded on appropriate use of instance vs. local variables, use of methods, and passing parameters and returning appropriate values.
    +1. The 'Statistics" class MUST provide "mutator" and "accessor" methods that are required to access values or to modify the values of any variable. REMEMBER ALL VARIABLES ARE DECLARED TO BE "private"!!+
    +2. You should implement methods to verify the data, as detailed above. The methods should return boolean values indicating whether the data is acceptable or not.+

    Sorry to hear about your problems - lack of time, having fallen behind, imminent failure etc - but none of these are Java problems.
    This site deals with Java problems: compiler or runtime behaviour that people can't understand. If you have problems of that sort (and especially if solving those problems would help with the problems you did describe) then post them.
    Otherwise you would seem to be in the wrong place.

  • Need Help for Java Homework Assignment, Can someone Please help me ?

    This is the program that I am supposed to write, and I am terrible confused, as it takes at least 3 different files.
    Write a class named GroceryList that representss a person's list of items to buy from the market, and another class named GroceryItemOrder that represents a request to purchase a particular item in a given quantity. (I.E. four boxes of cookies).
    **The GroceryList class should use an array field to store the grocery items, as well as keeping track of its size (number of items in the list so far). Assume that a grocery list will have no more than 10 items. A GrocerList object should have the following methods:
    public GroceryList()
    Constructs a new empty grocery list.
    public void add(GroceryItemOrder item)
    Adds the given item order to this list, if the list is not full (i.e., has fewer than 10 items).
    public double getTotalCost()
    Returns the total sum of all grocery item orders in this list.
    The GroceryItemOrder class should store an item quantity and a price per unit. A GroceryItemOrder object should have the following methods:
    public GrocerItemOrder(String name, int quantity, double pricePerUnit)
    Constructs an item order to purchase the item with the given name, in the given quantity, which costs the given pricer per unit.
    public double getCost()
    Returns the total cost of this item in its given quantity. I.E. 4 boxes of cookies that cost 2.30 per unit, have a total cost of 9.20.
    public void setQuantity(int quantity)
    Sets the grocery item's quantity to be the given value.
    Any suggestions would be sincerely appreciated.
    Thanks.

    Pete,
    I having difficulty with the main class, and getting console to store a users input into a string array ... I will post the code that I have so far. Sorry I am trying real hard to learn ... and just having a frustrating time.
    This is what I have in the main file.
    import java.util.*;
    public class Chapter_8 {
         public static void main(String []args){
              Scanner console = new Scanner(System.in);
              System.out.println("Please enter the first item of your list");
              String[]GroceryList = console.next();
              System.out.println("Please enter the next item of your list");
              String[]GroceryList = console.next();
              System.out.println("How many would you like to buy?");
              int quantity = consolenextInt();
         }This is what I have in the GroceryItem Class file:
    public class GroceryList{
    public GroceryList(){
    Static String []GroceryList ={"beans", "macaroni", "milk", "cheese", "bread", "eggs","hamburger","Hotdogs","peas","cookies"};
    for(int i=0;i<5;i++){
    System.out.println(GroceryList);
    And the final file that I have is the GroceryItemOrder Class file:public GroceryItemOrder(String name, int quantity, double pricePerUnit){
    this.name = name;
    this.quantity = quantity;
    this.pricePerUnit = pricePerUnit;
    public double getCost(){
    public void setQuantity(int quantity){
    Sorry, I know it isn't much, that's why I am frustrated.
    Thanks.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Help with Java Printing-Custom paper sizes

    Hi,
    I'm trying to print documents with custom paper sizes out of java.
    I can print fine when I don't try to set the MediaSize to a custom size or when I use already named constants like: "MediaSizeName.JIS_B4"
    The error message I get is this:
    java.lang.ClassCastException
         at javax.print.attribute.AttributeSetUtilities.verifyAttributeValue(Unknown Source)
         at javax.print.attribute.HashAttributeSet.add(Unknown Source)
         at hello.Printy.printDocument(Printy.java:103)
         at hello.Printy.main(Printy.java:135)
    The offending line(103) looks like this:
    pras.add(new MediaSize(1,10,MediaSize.INCH ));The function that its from looks like this:
    public  void printDocument()
    try
              System.out.println("input file name is");
         System.out.println(inputFileName);
    PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
    DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
    PrintService printService[] = PrintServiceLookup.lookupPrintServices(flavor, pras);
    PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();
    PrintService printPrintService = null;
    // didn't work pras.add(new MediaSize(1,10,MediaSize.INCH) );
    PrintService service = ServiceUI.printDialog(null, 200, 200,printService, defaultService, flavor, pras);
    if (service != null)
         System.out.println("There is a service aunty-may!!");
    DocPrintJob job = service.createPrintJob();
    FileInputStream fis = new FileInputStream(getInputFileName());
    DocAttributeSet das = new HashDocAttributeSet();
    //pras.add(new MediaSize((float)3.25, (float)4.75, Size2DSyntax.INCH ) );
    // - works
    //pras.add(MediaSizeName.JIS_B4);
    pras.add(new MediaSize(1,10,MediaSize.INCH ));
    //pras.add(new MediaSize(1,10,MediaSize.INCH) );
         System.out.println("Doc has been set to custom size");
    Doc doc = new SimpleDoc(fis, flavor, null);
    job.print(doc, pras);
         System.out.println("any doc for you?");
    catch (Exception e)
    e.printStackTrace();
    }Any help with this would be greatly appreciated. I'm new to java but I've programmed a bunch in c++.

    Hmm ... no real help, but I found this note in the API:
    MediaSize is not yet used to specify media. Its current role is as a mapping for named
    media (see MediaSizeName). Clients can use the mapping method
    MediaSize.getMediaSizeForName(MediaSizeName) to find the physical dimensions of
    the MediaSizeName instances enumerated in this API. This is useful for clients which
    need this information to format & paginate printing.

  • Help with RMI university assignment

    Hi everybody,
    The assignment asks for the definition of three remote interfaces ICompany, IProject and IStaff, define one 1:M relationship (ICompany -> IProject) and print on the console the company together with the projects they have placed. There is no requirement for a DB therefore i've create a method on the server
    populateDummyDB(ProjectImpl proj)that fills a Vector with projects with their coresponding company ID's.
    I've also created a company instance on the server which i successfully print on the client by callingprintCompany(Object obj) but i need help with theprintProjects() so that as soon the company is printed it searches the Vector for projects that have the same companyID matches the PK with the FK and print those projects.
    Any help will be more than welcome.
    Regards,
    Nick Paicopoulos
    BSc Applied Computing.

    Thanks for the reply and sorry for the vagueness.
    The company is created and bound to RMI on the Server
    CompanyImpl myCom = new CompanyImpl("101234", "WH Smith",
                        "Nick Parks", null);
    myCom.bindToRMI("com1"); also on the Server the Vector that is defined in the ProjectImpl.java is populated
    public static void populateDummyDB(ProjectImpl proj)
                throws RemoteException {
            proj.addProject(new ProjectImpl("Project A", "10 Feb 2005", 11000,
                    "101234", null, null));
            proj.addProject(new ProjectImpl("Project B", "16 Feb 2005", 8700,
                    "178745", null, null));
            proj.addProject(new ProjectImpl("Project C", "19 Feb 2005", 17400,
                    "130928", null, null));
            proj.addProject(new ProjectImpl("Project D", "27 Feb 2005", 12800,
                    "178745", null, null));
            proj.addProject(new ProjectImpl("Project E", "04 Mar 2005", 9760,
                    "101234", null, null));
            proj.addProject(new ProjectImpl("Project F", "09 Mar 2005", 5340,
                    "178745", null, null));
            proj.addProject(new ProjectImpl("Project G", "13 Mar 2005", 15290,
                    "101234", null, null));
            proj.addProject(new ProjectImpl("Project H", "17 Mar 2005", 5780,
                    "101234", null, null));
            proj.addProject(new ProjectImpl("Project I", "23 Mar 2005", 20100,
                    "130928", null, null));
            proj.addProject(new ProjectImpl("Project J", "30 Mar 2005", 6780,
                    "130928", null, null));
    } The company is printed successfully on the Client
    public class HKClientView{
        public static void main(String[] args) {
            HKClientView cmdUI = new HKClientView();
        public static final String SERVER_NAME = "localhost";
        public HKClientView() {
            ICompany yourCom = getRemoteCompany();
            try {
                CompanyTO yourComData = yourCom.getCompanyData();
                printCompany(yourComData);
    //            printProjects();
            } catch (RemoteException re) {
                System.out.println("Exception thrown while creating company "
                        + "instance! " + re);
        private ICompany getRemoteCompany() {
            ICompany myCompany = null;
            ProjectImpl myProject = null;
            try {
                myCompany = (ICompany) Naming.lookup("//" + SERVER_NAME + "/com1");
            } catch (Exception e) {
                System.out.println("Exception thrown while creating company "
                        + "instance! " + e);
            return myCompany;
        private void printCompany(Object obj) {
            System.out.println(obj.toString());
    } If you look closely at my dummy DB table four out of the ten projects belong to the company that i've created since the have common companyID = "101234". How can i get those projects printed on the Client?
    Regards,
    Nick Paicopoulos.

  • Need Help with Java Homework

    This is my first post here, seeking some help with my java homework. I am required to create a program to write out a receipt for a pizza company: name of company, total number of pizzas, costs (including tax etc), and print out the receipt after taking an order from the customer.
    This is a beginner's java class and my book isn't very good at explaining (mainly because it says "will be discussed in ch 14" when we're in ch 1-3 and it's an essential part of the program).
    But anyways, if anyone is up right now, would be helpful for some help. I have a general idea of what I wanna do, but the program so far is very messy and incomplete and having trouble getting it to look nice and proper.

    well there were two ways of doing this, im only 2 weeks new in java so bear with me.....I was gonna set 3 classes, one appclass, one order form, and one receipt. I was told you can combine the order and receipt in 1 class, but I thought doing 3 woudl be better to help me learn more...anyways, I haven't worked on the appclass yet, but for the order I have a very messy set of codes. I know that it's wrong but it's a start, im looking for any input cause the book does not explain very much.
    For the order class, I will be doing showinputdialog boxes for how many pizzas, the sizes, and the toppings. Here is what I have so far ( i know it is VERY messy and disorganized but I am a bit lost in where I should go next):
    * @author AlexNguyen
    * To take the order with number of pizzas and toppings
    package project2;
    import javax.swing.JOptionPane;
    public class Order {
         public int NumberOfPizzas;
         public char Pepperoni;
         public char Sausage;
         public char Cheese;
         public Order(int n) {
         NumberOfPizzas = n;
         JOptionPane.showInputDialog("Enter Number of Pizzas"));
    String ptype; {
         public void start();
         public void takeOrder();
         public void writeReceipt();
              public void takeOrder();
              ptype = Topping
    public String selectPizza(char P, char S, char C) {
         Pepperoni = P;
         Sausage = S;
         Cheese = C;
    public void numPizza(int numberOfPizzas) {
         num = numberOfPizzas;
    JOptionPane.showInputDialog("Topping for Pizza?");
    JOptionPane.showInputDialog("Pizza Size?");
    JOptionPane.showInputDialog("Number of Pizzas?");
    }

  • Collage Students need help with Java project(Email Server) whats analysis?

    Hi im studying in collage at the moment and i have just started learning java this semester, the thing is my teacher just told us to do an project in java , since we just started the course and i dont have any prior knowledge about java i was wondering if some one could help me with the project.
    i choose Email Sevice as my project and we have to submit an analysis and design document , but how the hell am i suppose to know what analysis is ? i just know we use ER diagrams & DFD's in the design phase but i dont know what analysis means ?
    could some one tell me what analysis on an email service might be? and what analysis on a subject means? is it the codeing involved or some thing coz the teacher told us not to do any codeing yet so im completly stumped,
    oh and btw we are a group of 3 students who are asking u the help here coz all of us in our class are stupmed ?

    IN case any one is interested this is the analysis i wrote
    ANALYSIS
    Analysis means figuring out what the problem is, maybe what kinds of solutions might be appropriate
    1.     Introduction:-
    The very definition of analysis is an investigation of the component parts of a whole and their relations in making up the whole. The Analysis done here is for an emailing service called Flashmail, the emailing service is used to send out mails to users registered with our service, these users and there log activities will be stored in some where, the most desirable option at this time is a Database, but this can change as the scope of the project changes.
    2.     Customer Analysis:-
    We are targeting only 30 registered users at the moment but this is subject to change as the scale changes of the project .Each user is going to be entitled to 1MB of storage space at this time since we lack the desired infrastructure to maintain anything higher than 1MB but the end vision of the project is to sustain 1000 MB of storage space while maintaining a optimal bandwidth allocation to each user so as to ensure a high speed of activity and enjoyment for the Customer.
    The Service will empower the user to be able to send, read, reply, and forward emails to there specified locations. Since we are working on a limited budget we can�t not at this time enable the sending of attachments to emails, but that path is also left open by modularity of java language, so we can add that feature when necessary.
    3.     Processor Load Analysis:-
    The number of messages per unit time processing power will be determined on hand with various algorithms, since it is best not to waste processor power with liberally distributing messages per unit time. Hence the number of messages will vary with in proportion to the number of registered users online at any given time.
    4.     Database Decision Analysis:-
    The High level Requirements of the service will have to be decided upon, the details of which can be done when we are implementing the project itself. An example of high level requirements are database management, we have chosen not to opt for flat files because of a number of reasons, first off a flat files are data files that contain records with no structured relationships additional knowledge is required to interpret these files such as the file format properties. The disadvantages associated with flat files are that they are not fast, they can only be read from top to bottom, and usually they have to be read all the way through. Though there is are advantages of Flat files they are that it takes up less space than a structured file. However, it requires the application to have knowledge of how the data is organized within the file.
    Good databases have key advantage over flat files concurrency. When you just read stuff from file it�s easy, but tries to synchronize multiple updates or writes into flat file from scripts that run in different process spaces.
    Whereas a flat file is a relatively simple database system in which each database is contained in a single table. In contrast, relational database systems can use multiple tables to store information, and each table can have a different record format.
    5.     Networking Analysis:-
    Virtually every email sent today is sent using two popular protocols known as SMTP (Simple Mail Transfer Protocol) and MIME (Multipurpose Internet Mail Extensions).
    1.     SMTP (Simple Mail Transfer Protocol)
    The SMTP protocol is the standard used by mail servers for sending and receiving email. In order to send email we will first establish a network connection to our SMTP server. Once you have finished sending your email message it is necessary that you disconnect from the SMTP server
    2.     MIME (Multipurpose Internet Mail Extensions)
    The MIME protocol is the standard used when composing email messages.

Maybe you are looking for