Need Help With D&D Program

Hi, I'm not sure if I'm allowed to post questions on this forum but I can't find anywhere to talk to helpful people about programming.
I'm making a dnd interface for JComponents. So far I've made a simple program that has a Component that can be lifted from a container and braught to the glass pane then later moved to anywhere on the screen and dropped into the container below it. Here's where my problems come:
1) Rite now my 'Movable Component' is a JPanel which is just colored in. I want to either take a Graphic2d from a JComponent/Component and draw it on the JPanel or change the JPanel to the component I want to paint and disable the component.
The problem with getting the Graphics2d is that if the component isn't on the screen it doesn't make a graphic object. I tried messing with the ui delicate and overriding parental methods for paintComponent, repaint, and that repaintChildren(forget name) but I haven't had luck getting a good graphics object. I was thinking of, at the beginning of running the program, putting 1 of each component onto the screen for a second then removing it but I'd rather not. I'd also like to change the graphics dynamicly if someone stretches the component there dropping and what not.
The problem with disabling is that it changes some of the visual features of Components. I want to be able to update the Component myself to change how it looks and I don't want disabling to gray out components.
I mainly just dont want the components to do any of there normal fuctions. This is for a page builder, by the way.
Another problem I'm having is that mouseMotionListener is allowing me to select 2 components that are on top of one another when there edges are near each other. I don't know if theres a fix to this other than changing the Java Class.
My next problem is a drop layout manager, but I'm doing pretty good with that rite now. It'll problem just move components out of the way of the falling component.
One last thing I need help with is that I don't want the object that's being carried to go across the menu bar and certain areas. When I'm having the object being carried I have it braught up to the glass pane which allows it to move anywhere. Does anyone have any idea how I could prevent the component from being over the menu bars and other objects? I might have to make 1 panel is the movable area that can then be broken down into the 'component bank', 'building page' and whatever else I'm gonna need.
This is all just test code to get together for when I make the real program but I need to make sure it'll be possible without a lot of hacking of code.
Sorry for the length. Thanks for any help you can give.

The trick to making viewable components that have no behaviour, is to render them onto an image of some sort (eg a BufferedImage). You can then display the Image on a JLabel that can be dragged around the desktop.
Here is a piece of code that does the component rendering for you. This particular example uses a fixed component size, but you can modify that as you choose of course...public class JComponentImage
     private static GraphicsConfiguration gConfig;
     private static Dimension compSize = new Dimension(80, 22);
     private static Image image = null;
     public static Image getImage(Class objectClass)
          if (gConfig == null)
               GraphicsEnvironment gEnv = GraphicsEnvironment.getLocalGraphicsEnvironment();
               GraphicsDevice gDevice = gEnv.getDefaultScreenDevice();
               gConfig = gDevice.getDefaultConfiguration();
          image = gConfig.createCompatibleImage(compSize.width, compSize.height);
          JComponent jc = (JComponent) ObjectFactory.instantiate(objectClass);
          jc.setSize(compSize);
          Graphics g = image.getGraphics();
          g.setColor(Color.LIGHT_GRAY);
          g.fillRect(0, 0, compSize.width, compSize.height);
          g.setColor(Color.BLACK);
          jc.paint(g);
          return image;
}And here is the class that makes the dragable JLabel using the class above...public class Dragable extends JLabel
     private static DragSource dragSource = DragSource.getDefaultDragSource();
     private static DragGestureListener dgl = new DragMoveGestureListener();
     private static TransferHandler th = new ObjectTransferHandler();
     private Class compClass;
     private Image image;
     Dragable(Class compClass)
          this.compClass = compClass;
          image = JComponentImage.getImage(compClass);
          setIcon(new ImageIcon(image));
          setTransferHandler(th);
          dragSource.createDefaultDragGestureRecognizer(this,
                                                      DnDConstants.ACTION_COPY,
                                                      dgl);
     public Class getCompClass()
          return compClass;
}Oh and here is ObjectFactory which simply instantiates Objects of a given class and sets their text to their classname (very crudely)...public class ObjectFactory
     public static Object instantiate(Class objectClass)
          Object o = null;
          try
               o = objectClass.newInstance();
          catch (Exception e)
               System.out.println("ObjectFactory#instantiate: " + e);
          String name = objectClass.getName();
          int lastDot = name.lastIndexOf('.');
          name = name.substring(lastDot + 1);
          if (o instanceof JLabel)
               ((JLabel)o).setText(name);
          if (o instanceof JButton)
               ((JButton)o).setText(name);
          if (o instanceof JTextComponent)
               ((JTextComponent)o).setText(name);
          return o;
}Two more classes required by this codepublic class ObjectTransferHandler extends TransferHandler {
     private static DataFlavor df;
      * Constructor for ObjectTransferHandler.
     public ObjectTransferHandler() {
          super();
          try {
               df = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType);
          } catch (ClassNotFoundException e) {
               Debug.trace(e.toString());
     public Transferable createTransferable(JComponent jC) {
          Transferable t = null;
          try {
               t = new ObjectTransferable(((Dragable) jC).getCompClass());
          } catch (Exception e) {
               Debug.trace(e.toString());
          return t;
     public int getSourceActions(JComponent c) {
          return DnDConstants.ACTION_MOVE;
     public boolean canImport(JComponent comp, DataFlavor[] flavors) {
          if (!(comp instanceof Dragable) && flavors[0].equals(df))
               return true;
          return false;
     public boolean importData(JComponent comp, Transferable t) {
          JComponent c = null;
          try {
               c = (JComponent) t.getTransferData(df);
          } catch (Exception e) {
               Debug.trace(e.toString());
          comp.add(c);
          comp.validate();
          return true;
public class ObjectTransferable implements Transferable {
     private static DataFlavor df = null;
     private Class objectClass;
     ObjectTransferable(Class objectClass) {
          try {
               df = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType);
          } catch (ClassNotFoundException e) {
               System.out.println("ObjectTransferable: " + e);
          this.objectClass = objectClass;
      * @see java.awt.datatransfer.Transferable#getTransferDataFlavors()
     public DataFlavor[] getTransferDataFlavors() {
          return new DataFlavor[] { df };
      * @see java.awt.datatransfer.Transferable#isDataFlavorSupported(DataFlavor)
     public boolean isDataFlavorSupported(DataFlavor testDF) {
          return testDF.equals(df);
      * @see java.awt.datatransfer.Transferable#getTransferData(DataFlavor)
     public Object getTransferData(DataFlavor arg0)
          throws UnsupportedFlavorException, IOException {
          return ObjectFactory.instantiate(objectClass);
}And of course the test class:public class DragAndDropTest extends JFrame
     JPanel leftPanel = new JPanel();
     JPanel rightPanel = new JPanel();
     Container contentPane = getContentPane();
     Dragable dragableJLabel;
     Dragable dragableJButton;
     Dragable dragableJTextField;
     Dragable dragableJTextArea;
      * Constructor DragAndDropTest.
      * @param title
     public DragAndDropTest(String title)
          super(title);
          dragableJLabel = new Dragable(JLabel.class);
          dragableJButton = new Dragable(JButton.class);
          dragableJTextField = new Dragable(JTextField.class);
          dragableJTextArea = new Dragable(JTextArea.class);
          leftPanel.setBorder(new EtchedBorder());
          BoxLayout boxLay = new BoxLayout(leftPanel, BoxLayout.Y_AXIS);
          leftPanel.setLayout(boxLay);
          leftPanel.add(dragableJLabel);
          leftPanel.add(dragableJButton);
          leftPanel.add(dragableJTextField);
          leftPanel.add(dragableJTextArea);
          rightPanel.setPreferredSize(new Dimension(500,500));
          rightPanel.setBorder(new EtchedBorder());
          rightPanel.setTransferHandler(new ObjectTransferHandler());
          contentPane.setLayout(new BorderLayout());
          contentPane.add(leftPanel, "West");
          contentPane.add(rightPanel, "Center");
     public static void main(String[] args)
          JFrame frame = new DragAndDropTest("Drag and Drop Test");
          frame.pack();
          frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
          frame.setVisible(true);
}I wrote this code some time ago, so it won't be perfect but hopefully will give you some good ideas.
Regards,
Tim

Similar Messages

  • Need help with my addressbook program

    hi,
    i need help with my program here. this one should works as:
    - saves user input into a txt file
    - displays name of the saved person on the jlist whenever i run the program
    - displays info about the person when clicked via textboxes given by reading the txt file where the user inputs are
    - should scroll when the list exceeds the listbox
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.JList;
    import java.awt.event.ActionListener;
    import java.io.*;
    import javax.swing.event.*;
    import java.io.FilterInputStream;
    public class AddressList extends JPanel implements ActionListener
         JTextField txt1 = new JTextField();
         JTextField txt2 = new JTextField();
         JTextField txt3 = new JTextField();
         DefaultListModel mdl = new DefaultListModel();
         JList list = new JList();
         JScrollPane listScroller = new JScrollPane(list);
         ListSelectionModel listSelectionModel;
         File fob = new File("Address3.txt");
         String name;
         char[] chars;     
         public void ListDisplay()
              try
                   RandomAccessFile rand = new RandomAccessFile(fob,"rw");
                   BufferedReader br = new BufferedReader(new FileReader("Address3.txt"));
                   if(fob.exists())
                         while((name = rand.readLine()) != null)
                              chars = name.toCharArray();
                              if(chars[0] == '*')
                                   mdl.addElement(name);
                                   list.setModel(mdl);
                              if(chars[0] == '#')
                                   continue;
                    else
                        System.out.println("No such file..");
              catch(IOException a)
                         System.out.println(a.getMessage());
         public AddressList()
              this.setLayout(null);
              listSelectionModel = list.getSelectionModel();
            listSelectionModel.addListSelectionListener(new ListInfo());
              list.setBounds(10,40,330,270);
              listScroller.setBounds(320,40,20,100);
              add(list);
              add(listScroller);
              JLabel lbl4 = new JLabel("Name: ");
              lbl4.setBounds(400,10,80,30);
              add(lbl4);
              JLabel lbl5 = new JLabel("Cellphone #: ");
              lbl5.setBounds(400,50,80,30);
              add(lbl5);
              JLabel lbl6 = new JLabel("Address: ");
              lbl6.setBounds(400,90,80,30);
              add(lbl6);
              JLabel lbl7 = new JLabel("List ");
              lbl7.setBounds(10,10,100,30);
              add(lbl7);
              txt1.setBounds(480,10,200,30);
              add(txt1);
              txt2.setBounds(480,50,200,30);
              add(txt2);
              txt3.setBounds(480,90,200,30);
              add(txt3);
              JButton btn1 = new JButton("Add");
              btn1.setBounds(480,130,100,30);
              btn1.addActionListener(this);
              btn1.setActionCommand("Add");
              add(btn1);
              JButton btn2 = new JButton("Save");
              btn2.setBounds(480,170,100,30);
              btn2.addActionListener(this);
              btn2.setActionCommand("Save");
              add(btn2);
              JButton btn3 = new JButton("Cancel");
              btn3.setBounds(480,210,100,30);
              btn3.addActionListener(this);
              btn3.setActionCommand("Cancel");
              add(btn3);
              JButton btn4 = new JButton("Close");
              btn4.setBounds(480,250,100,30);
              btn4.addActionListener(this);
              btn4.setActionCommand("Close");
              add(btn4);
         public static void main(String[]args)
              JFrame frm = new JFrame("Address List");
              AddressList panel = new AddressList();
              frm.getContentPane().add(panel,"Center");
              frm.setSize(700,350);
              frm.setVisible(true);
              panel.ListDisplay();
         public void actionPerformed(ActionEvent e)
              String cmd;
              cmd = e.getActionCommand();
              if(cmd.equals("Add"))
                   txt1.setText("");
                   txt2.setText("");
                   txt3.setText("");
              else if(cmd.equals("Save"))
                   mdl.addElement(txt1.getText());
                   list.setModel(mdl);
                   try
                   RandomAccessFile rand = new RandomAccessFile(fob,"rw");
                   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
                   LineNumberReader line = new LineNumberReader(br);
                    if(fob.exists())
                              rand.seek(fob.length());
                              rand.writeBytes("* " + txt1.getText());
                              rand.writeBytes("\r\n" + "# " + txt2.getText());
                              rand.writeBytes("\r\n" + "# " + txt3.getText() + "\r\n");
                    else
                         System.out.println("No such file..");
                        txt1.setText("");
                        txt2.setText("");
                        txt3.setText("");
                    catch(IOException a)
                         System.out.println(a.getMessage());
              else if(cmd.equals("Cancel"))
                   txt1.setText("");
                   txt2.setText("");
                   txt3.setText("");
              else if(cmd.equals("Close"))
                   System.exit(0);
    class ListInfo implements ListSelectionListener
         public void valueChanged(ListSelectionEvent e)
              ListSelectionModel lsm = (ListSelectionModel)e.getSource();
              int minIndex = lsm.getMinSelectionIndex();
            int maxIndex = lsm.getMaxSelectionIndex();
              try //*this one should display the info of the person whenever i click the person's name at the list box via textbox.. but i cant seem to get it right since it always display the info of the first person inputed.. i tried to get the program to display them whenever it reads lines with * on them....
                   File fob = new File("Address3.txt");
                   RandomAccessFile rand = new RandomAccessFile(fob,"rw");
                   BufferedReader br = new BufferedReader(new FileReader("Address3.txt"));
                   LineNumberReader line = new LineNumberReader(br);
                   if(fob.exists())
                              for(int i = minIndex; i<=maxIndex; i++)
                                   if(lsm.isSelectedIndex(i))
                                        while((name = rand.readLine()) != null)
                                             chars = name.toCharArray();
                                             if(chars[0] == '#')
                                                  continue;
                                             if(chars[0] == '*')
                                                  txt1.setText(rand.readLine());
                                                 txt2.setText(rand.readLine());
                                                 txt3.setText(rand.readLine());
                    else
                              System.out.println("No such file..");
              catch(IOException a)
                         System.out.println(a.getMessage());
    }the only problem now is about how it should display the right info about the person whenever i click its name on the list.. something about file reading or something, i just cant figure it out.
    and also about how to make it scroll once it exceeds the list.. i cant make it work, maybe something about wrong declaration..
    thanks in advance..
    Edited by: syder on Mar 14, 2008 2:26 AM

    Like said before, do one thing at a time. At startup, something like:
    //put all the content in a list
    ArrayList<String> lines = new ArrayList<String>();
    while(String line=rand.readLine()!=null) {
        lines.add(line);
    }If you follow the good advice to create a class to encapsulate the entries, you could populate a list of such entries like this:
    static final int ENTRY_SIZE = 3;//you have 3 fields now, better to have a constant if that changes
    ArrayList<Entry> entries = new ArrayList<Entry>();
    for(int i=0; i<lines.size(); i+=ENTRY_SIZE) {
        Entry entry = new Entry(lines.get(i), lines.get(i+1), lines.get(i+2);
        entries.add(newEntry);
    }You could also do both of the above in one run, but I think you will understand better what's happening if you do one thing at a time.
    If you don't want to put the entries in an encapsulating class, you can still access this without looping:
    int listStartIdx = <desired_entry_index>*ENTRY_SIZE;
    String att1 = lines.get(listStartIdx).substring(1);
    String att2 = lines.get(listStartIdx+1).substring(1);
    String att3 = lines.get(listStartIdx+2).substring(1);

  • Need help with a rudimentary program

    I'm sort of new at this so i need help with a few things... I'm making a program to compile wages and i need answers with three things: a.) what are the error messages im getting meaning? b.) How can i calculate the state tax as 2% of my gross pay with the first $200 excluded and c.) how can i calculate the local tax as a flat $10 with $2 deducted for each dependant. any help is appreciated
    Here is what i have so far:
    public class WagesAsign1
              public static void main(String[] args)
                   int depend=4;
                   double hrsWork=40;
                   double payRate=15;
                   double grossPay;
                   grossPay=payRate*hrsWork;
                   double statePaid;
                   double stateTax=2.0;
                   statePaid=grossPay*(stateTax/100);
                   double localPaid;
                   double localTax=10.0;
                   localPaid=grossPay*(localTax/100);
                   double fedPaid;
                   double fedTax=10.0;
                   double taxIncome;
                   fedPaid=taxIncome*(fedTax/100);
                   taxIncome=grossPay-(statePaid+localPaid);
                   double takeHome;
                   System.out.println("Assignment 1 Matt Foraker\n");
                   System.out.println("Hours worked="+hrsWork+" Pay rate $"+payRate+" per/hour dependants: "+depend);
                   System.out.println("Gross Pay $"+grossPay+"\nState tax paid $"+statePaid+"\nLocal tax paid $"+localPaid+"\nFederal tax paid $"+fedPaid);
                   System.out.println("You take home a total of $"+takeHome);
    and these are the error messages so far:
    WagesAsign1.java:23: variable taxIncome might not have been initialized
                   fedPaid=taxIncome*(fedTax/100);
    ^
    WagesAsign1.java:29: variable takeHome might not have been initialized
                   System.out.println("You take home a total of $"+takeHome);
    ^

    edit: figured it out... please delete post
    Message was edited by:
    afroryan58

  • Need help with a simple program (should be simple anyway)

    I'm (starting to begin) writing a nice simple program that should be easy however I'm stuck on how to make the "New" button in the file menu clear all the fields. Any help? I'll attach the code below.
    ====================================================
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Message extends JFrame implements ActionListener {
         public void actionPerformed(ActionEvent evt) {
         text1.setText(" ");
         text2.setText("RE: ");
         text3.setText(" ");
         public Message() {
         super("Write a Message - by Kieran Hannigan");
         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         setSize(370,270);
         FlowLayout flo = new FlowLayout(FlowLayout.RIGHT);
         setLayout(flo);
         //Make the bar
         JMenuBar bar = new JMenuBar();
         //Make "File" on Menu
         JMenu File = new JMenu("File");
         JMenuItem f1 = new JMenuItem("New");f1.addActionListener(this);
         JMenuItem f2 = new JMenuItem("Open");
         JMenuItem f3 = new JMenuItem("Save");
         JMenuItem f4 = new JMenuItem("Save As");
         JMenuItem f5 = new JMenuItem("Exit");
         File.add(f1);
         File.add(f2);
         File.add(f3);
         File.add(f4);
         File.add(f5);
         bar.add(File);
         //Make "Edit" on menu
         JMenu Edit = new JMenu("Edit");
         JMenuItem e1 = new JMenuItem("Cut");
         JMenuItem e2 = new JMenuItem("Paste");
         JMenuItem e3 = new JMenuItem("Copy");
         JMenuItem e4 = new JMenuItem("Repeat");
         JMenuItem e5 = new JMenuItem("Undo");
         Edit.add(e5);
         Edit.add(e4);
         Edit.add(e1);
         Edit.add(e3);
         Edit.add(e2);
         bar.add(Edit);
         //Make "View" on menu
         JMenu View = new JMenu("View");
         JMenuItem v1 = new JMenuItem("Bold");
         JMenuItem v2 = new JMenuItem("Italic");
         JMenuItem v3 = new JMenuItem("Normal");
         JMenuItem v4 = new JMenuItem("Bold-Italic");
         View.add(v1);
         View.add(v2);
         View.add(v3);
         View.addSeparator();
         View.add(v4);
         bar.add(View);
         //Make "Help" on menu
         JMenu Help = new JMenu("Help");
         JMenuItem h1 = new JMenuItem("Help Online");
         JMenuItem h2 = new JMenuItem("E-mail Programmer");
         Help.add(h1);
         Help.add(h2);
         bar.add(Help);
         setJMenuBar(bar);
         //Make Contents of window.
         //Make "Subject" text field
         JPanel row2 = new JPanel();
         JLabel sublabel = new JLabel("Subject:");
         row2.add(sublabel);
         JTextField text2 = new JTextField("RE:",24);
         row2.add(text2);
         //Make "To" text field
         JPanel row1 = new JPanel();
         JLabel tolabel = new JLabel("To:");
         row1.add(tolabel);
         JTextField text1 = new JTextField(24);
         row1.add(text1);
         //Make "Message" text area
         JPanel row3 = new JPanel();
         JLabel Meslabel = new JLabel("Message:");
         row3.add(Meslabel);
         JTextArea text3 = new JTextArea(6,22);
         messagearea.setLineWrap(true);
         messagearea.setWrapStyleWord(true);
         JScrollPane scroll = new JScrollPane(text3,
                                  JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                                  JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
         //SpaceLine
         JPanel spaceline = new JPanel();
         JLabel spacer = new JLabel(" ");
         spaceline.add(spacer);
         row3.add(scroll);
         add(row1);
         add(row2);
         add(spaceline);
         add(spaceline);
         add(row3);
         setVisible(true);
         public static void main(String[] arguments) {
         Message Message = new Message();
    }

    persiandude wrote:
    Topic: Need help with if, else, and which statements and loops.
    How would I display 60 < temp. <= 85 in java
    System.out.println("60 < temp. <= 85 in java");
    another question is how do I ask a question like want to try again (y/n) after a output and asking that everytime I type in yes after a output and terminate when saying No.Sun's [basic Java tutorial|http://java.sun.com/docs/books/tutorial/]
    Sun's [New To Java Center|http://java.sun.com/learning/new2java/index.html].Includes an overview of what Java is, instructions for setting up Java, an intro to programming (that includes links to the above tutorial or to parts of it), quizzes, a list of resources, and info on certification and courses.
    [http://javaalmanac.com|http://javaalmanac.com]. A couple dozen code examples that supplement [The Java Developers Almanac|http://www.amazon.com/exec/obidos/tg/detail/-/0201752808?v=glance].
    jGuru. A general Java resource site. Includes FAQs, forums, courses, more.
    JavaRanch. To quote the tagline on their homepage: "a friendly place for Java greenhorns." FAQs, forums (moderated, I believe), sample code, all kinds of goodies for newbies. From what I've heard, they live up to the "friendly" claim.
    Bruce Eckel's [Thinking in Java|http://mindview.net/Books/DownloadSites] (Available online.)
    Joshua Bloch's [Effective Java|http://www.amazon.com/Effective-Java-2nd-Joshua-Bloch/dp/0321356683/ref=pd_bbs_1?ie=UTF8&s=books&qid=1214349768&sr=8-1]
    Bert Bates and Kathy Sierra's [Head First Java|http://www.amazon.com/exec/obidos/tg/detail/-/0596004656?v=glance].
    James Gosling's [The Java Programming Language|http://www.bookpool.com/sm/0321349806].

  • Need help with accessing the program.

    I need help with accessing my adobe creative cloud on my windows 8.1 laptop. I have an account but do not have an app. I need this for my online classes. Please help!

    Link for Download & Install & Setup & Activation may help
    -Chat http://www.adobe.com/support/download-install/supportinfo/

  • Need Help with simple array program!

    Hi, I have just recently started how to use arrays[] in Java and I'm a bit confused and need help designing a program.
    What this program does, it reads in a range of letters specified by the user. The user then enters the letters (a, b or c) and stores these characters into an array, which the array's length is equal to the input range the user would enter at the start of the program. The program is then meant to find how many times (a,b and c) appears in the array and the Index it first appears at, then prints these results.
    Here is my Code for the program, hopefully this would make sense of what my program is suppose to do.
    import B102.*;
    class Letters
         static int GetSize()
              int size = 0;
              boolean err = true;
              while(err == true)
                   Screen.out.println("How Many Letters would you like to read in?");
                   size = Keybd.in.readInt();
                   err = Keybd.in.fail();
                   Keybd.in.clearError();
                   if(size <= 0)
                        err = true;
                        Screen.out.println("Invalid Input");
              return(size);
         static char[] ReadInput(int size)
              char input;
              char[] letter = new char[size];
              for(int start = 1; start <= size; start++)
                   System.out.println("Please enter a letter (a, b or c) ("+size+" max), enter # to stop:");
                   input = Keybd.in.readChar();
                   while((input != 'a') && (input != 'b') && (input != 'c') && (input != '#'))
                        Screen.out.println("Invalid Input");
                        System.out.println("Please enter a letter (a, b or c) ("+size+" max, enter # to stop:");
                        input = Keybd.in.readChar();
                                    while(input == '#')
                                                 start == size;
                                                 break;
                   for(int i = 0; i < letter.length; i++)
                        letter[i] = input;
              return(letter);
         static int CountA(char[] letter)
              int acount = 0;
              for(int i = 0; i < letter.length; i++)
                   if(letter[i] == 'a')
                        acount++;
              return(acount);
         static int CountB(char[] letter)
              int bcount = 0;
              for(int i = 0; i < letter.length; i++)
                   if(letter[i] == 'b')
                        bcount++;
              return(bcount);
         static int CountC(char[] letter)
              int ccount = 0;
              for(int i = 0; i < letter.length; i++)
                   if(letter[i] == 'c')
                        ccount++;
              return(ccount);
         static int SearchA(char[] letter)
              int ia;
              for(ia = 0; ia < letter.length; ia++)
                   if(letter[ia] == 'a')
                        return(ia);
              return(ia);
         static int SearchB(char[] letter)
              int ib;
              for(ib = 0; ib < letter.length; ib++)
                   if(letter[ib] == 'b')
                        return(ib);
              return(ib);
         static int SearchC(char[] letter)
              int ic;
              for(ic = 0; ic < letter.length; ic++)
                   if(letter[ic] == 'c')
                        return(ic);
              return(ic);
         static void PrintResult(char[] letter, int acount, int bcount, int ccount, int ia, int ib, int ic)
              if(ia <= 1)
                   System.out.println("There are "+acount+" a's found, first appearing at index "+ia);
              else
                   System.out.println("There are no a's found");
              if(ib <= 1)
                   System.out.println("There are "+bcount+" b's found, first appearing at index "+ib);
              else
                   System.out.println("There are no b's found");
              if(ic <= 1)
                   System.out.println("There are "+ccount+" c's found, first appearing at index "+ic);
              else
                   System.out.println("There are no c's found");
              return;
         public static void main(String args[])
              int size;
              char[] letter;
              int acount;
              int bcount;
              int ccount;
              int ia;
              int ib;
              int ic;
              size = GetSize();
              letter = ReadInput(size);
              acount = CountA(letter);
              bcount = CountB(letter);
              ccount = CountC(letter);
              ia = SearchA(letter);
              ib = SearchB(letter);
              ic = SearchC(letter);
              PrintResult(letter, acount, bcount, ccount, ia, ib, ic);
              return;
    }     Some errors i get with my program are:
    When reading in the letters to store into the array, I get the last letter I entered placed into the entire array. Also I believe my code to find the Index is incorrect.
    Example Testing: How many letters would you like to read? 3
    Enter letter (a, b or c) (# to quit): a
    Enter letter (a, b or c) (# to quit): b
    Enter letter (a, b or c) (# to quit): c
    It prints "There are no a's'" (there should be 1 a at index 0)
    "There are no b's" (there should be 1 b at index 1)
    and "There are 3 c's, first appearing at index 0" ( there should be 1 c at index 2)
    The last thing is that my code for when the user enters "#" that the input of letters would stop and the program would then continue over to the counting and searching part for the letters, my I believe is correct but I get the same problem as stated above where the program takes the character "#" and stores it into the entire array.
    Example Testing:How many letters would you like to read? 3
    Enter letter (a, b or c) (# to quit): a
    Enter letter (a, b or c) (# to quit): #
    It prints "There are no a's'" (should have been 1 a at index 0)
    "There are no b's"
    and "There are no c's"
    Can someone please help me??? or does anyone have a program simular to this they have done and would'nt mind showing me how it works?
    Thanks
    lou87.

    Without thinking too much...something like this
    for(int start = 0; start < size; start++) {
                System.out.println("Please enter a letter (a, b or c) ("+size+" max), enter # to stop:");
                input = Keybd.in.readChar();
                while((input != 'a') && (input != 'b') && (input != 'c') && (input != '#')) {
                    Screen.out.println("Invalid Input");
                    System.out.println("Please enter a letter (a, b or c) ("+size+" max, enter # to stop:");
                    input = Keybd.in.readChar();
                if(input == '#') {
                        break;
                letter[start] = input;
            }you dont even need to do start = size; coz with the break you go out of the for loop.

  • Need help with spell checker program

    Hi
    I am writing a spell checker program and need help for a simple logic.I have "List" of correctly spelled words and a String array of wrong spelled words.How can I compare both and tell that for eg xyz word is not spelled correctly.

    BigDaddyLoveHandles wrote:
    To learn more about Map, take the collection tutorial: [http://java.sun.com/docs/books/tutorial/collections/index.html]
    (Actually, to me it sounds like you have a Set of correctly spelled words and another Set of words which may or may not be correctly spelled, and you want the difference...)That is what it sounds like to me also, and that is easy.
    JSG

  • Need Help with a JAVA programming assignment

    How do I write a JAVA program that could be used as the start of an MS-DOS/Windows simulation of the IEEE 802.3 protocol? I am to only code the parts necessary to build the 802.3 frame. For the initial implementation, the Checksum function need not be a CRC function, and the Destination and Source addresses wil be in input, stored, and output, and in dotted-decimal format.
    I need:
    1. A record to describe the frame, with each field being a (byte-) string of the required size, except that the Data field is of variable size. Although the "Source address" and "Destination address" would be 6 bytes for a real implementation, for this first implementation you can either assume they'll be text strings in the usual "dotted decimal" form (e.g. "14.04.05.18.01.25" as a typical example--from Tanenbaum, p. 429), or 6 hex digits.
    2. Suitable constant declarations for values such as the standard "Preamble" and "Start of Frame" values.
    3. Suitable functions to Get the three variable values "Destination address", "Source address", and "Data" from the standard input device.
    4. A suitable function to display each of the fields of a given frame in a format such as:
    Preamble: ...
    StartofFrame: ...
    Destination: ...
    etc.
    5. A suitable function to generate a "Pad" field if necessary.
    6. A "dummy" Checksum-generating function which just takes the first 32 bits (4 bytes) of the Data (or Data+Pad, if necessary) rather than an actual CRC algorithm.
    I have no experience with Java. Can you help me or start me in the right direction?
    Thanks...........TK

    If you have no experience with Java, then it seems to me your first step should be to start learning the language. But it's difficult to advise how, since we don't know anything about your background. There are many good books available on Java, some are for beginners and some are for advanced programmers, so I'd suggest you go somewhere that has a large selection and start looking for something that doesn't seem completely over your head.

  • Need help with java thread program

    Hi
    I have an applet which does some painting etc, i need to write a thread which runs in background, and if there is no user activity for 30 min will refresh the screen.
    I have one good thing that all user options go from one program so i know when user does some thing.
    How do i write this thread program?
    1. I need this program to start counter as soon as some activity is done by user
    2. When user does some thing stop this thread
    3. when user completes his action restart the thread with 30 min timer.
    4. when there is no activity for 30 min refresh the screen
    Any help will be really good
    Ashish

    Not sure what the problem is. Your pseudo code looks good to me.
    The only suggestion I would make is that your use a Timer so you don't have to worry about creating your own Thread. You schedule a Timer to fire in 30 minutes. Everytime you have activiity you cancel the timer and reschedule it.

  • Need Help with Simple Chat Program

    Hello Guys,
    I'm fairly new to Java and I have a quick question regarding a simple chat program in java. My problem is that I have a simple chat program that runs from its own JFrame etc. Most of you are probably familiar with the code below, i got it from one of my java books. In any case, what I'm attempting to do is integrate this chat pane into a gui that i have created. I attempted to call an instace of the Client class from my gui program so that I can use the textfield and textarea contained in my app, but it will not allow me to do it. Would I need to integrate this code into the code for my Gui class. I have a simple program that contains chat and a game. The code for the Client is listed below.
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.net.*;
    import javax.swing.*;
    public class Client
    extends JPanel {
    public static void main(String[] args) throws IOException {
    String name = args[0];
    String host = args[1];
    int port = Integer.parseInt(args[2]);
    final Socket s = new Socket(host, port);
    final Client c = new Client(name, s);
    JFrame f = new JFrame("Client : " + name);
    f.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent we) {
    c.shutDown();
    System.exit(0);
    f.setSize(300, 300);
    f.setLocation(100, 100);
    f.setContentPane(c);
    f.setVisible(true);
    private String mName;
    private JTextArea mOutputArea;
    private JTextField mInputField;
    private PrintWriter mOut;
    public Client(final String name, Socket s)
    throws IOException {
    mName = name;
    createUI();
    wireNetwork(s);
    wireEvents();
    public void shutDown() {
    mOut.println("");
    mOut.close();
    protected void createUI() {
    setLayout(new BorderLayout());
    mOutputArea = new JTextArea();
    mOutputArea.setLineWrap(true);
    mOutputArea.setEditable(false);
    add(new JScrollPane(mOutputArea), BorderLayout.CENTER);
    mInputField = new JTextField(20);
    JPanel controls = new JPanel();
    controls.add(mInputField);
    add(controls, BorderLayout.SOUTH);
    mInputField.requestFocus();
    protected void wireNetwork(Socket s) throws IOException {
    mOut = new PrintWriter(s.getOutputStream(), true);
    final String eol = System.getProperty("line.separator");
    new Listener(s.getInputStream()) {
    public void processLine(String line) {
    mOutputArea.append(line + eol);
    mOutputArea.setCaretPosition(
    mOutputArea.getDocument().getLength());
    protected void wireEvents() {
    mInputField.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
    String line = mInputField.getText();
    if (line.length() == 0) return;
    mOut.println(mName + " : " + line);
    mInputField.setText("");

    Thanks for ur help!i have moved BufferedReader outside the loop. I dont think i am getting exception as i can c the output once.What i am trying to do is repeat the process which i m getting once.What my method does is first one sends the packet to multicasting group (UDP) and other method receives the packets and prints.

  • Need help with basic Java programming

    I'm having a little bit of trouble with my code. For the sake of argument, I've removed the code I'm having trouble with, because I know it was inaccurate. I'm trying to create a loop so that this program will keep going through and through until the user enters an invalid variable. I thought the default after the case statements was supposed to make the system exit and output my message. Those two problems, the loop and the default, are what I'm really having problems with. My code is posted below.
    import javax.swing.JOptionPane;
    import java.util.Locale;
    import java.text.NumberFormat;
    public class Retail
    public static void main(String args[])
    String firstNum;
    String secondNum;
    String result;
    int prodNum;      //first number to input
    double quantity; //second number to input
    double total = 0.0;     //total of Prod * Quantity Sold for all items
    // To use American Dollar
    NumberFormat moneyFormat = NumberFormat.getCurrencyInstance( Locale.US );
    // first number entered as string
    firstNum = JOptionPane.showInputDialog( "Enter product number 1-5" );
    // second number entered as string
    secondNum = JOptionPane.showInputDialog( " Enter quantity of items sold" );
    // convert values to type double or int from type string
    prodNum = Integer.parseInt( firstNum );
    quantity = Double.parseDouble( secondNum);
    result="";
    if ( prodNum >=1 && prodNum <=5 ) {
    switch (prodNum)
    case 1: // 1st product
    total = 2.98 * quantity;
    break;
    case 2: // 2nd product
    total = 4.50 * quantity;
    break;
    case 3: // 3rd product
    total = 9.98 * quantity;
    break;
    case 4: //4th product
    total = 4.49 * quantity;
    break;
    case 5:
    total = 6.87 * quantity;
    break;
    default: JOptionPane.showMessageDialog( null, "Wrong product number entered" );
    JOptionPane.showMessageDialog( null, moneyFormat.format(total), "Total Price of Items Purchased", JOptionPane.INFORMATION_MESSAGE );
    System.exit(0);
    ***I know I need to put something in the user input message to state that any value other than 1-5 entered will cause the program to skip to the output, I'll put that in later.***

    When you post code, please use [code] and [/code] tags as described in Formatting Help on the message entry page. It makes it much easier to read and prevents accidental markup from array indices like [i].

  • Need Help with a Java programming exercise.

    I have to Write a program that reads two times in military format (0900, 1730) and prints the number of hours and minutes between two times. Supply your own test program. Here are two sample runs. User inputs are the numbers.
    Please enter the first time: 0900
    Please enter the second time: 1730
    8 hours 30 minutes
    Please enter the first time: 1730
    Please enter the second time: 0900
    15 hours 30 minutes
    Test Program I can write up myself. But the entire constructor I have no idea how to start. This is basic Java Coding. no C++ no importing anything.
    So far this is what I got and I'm sure it's wrong:
    public class TimeInterval
    private double hours;
    private double minutes;
    public TimeInterval(double Time1, double Time2)
    hours =
    minutes =
    }

    tad2382 wrote:
    Jverd,
    I'm guessing that in your early days on this forum you must have spent a lot of time explaining constructors, object creation, etc. Now, after some 40K posts to the forum, you figure newbies should just go and read the documentation. Is that what a lot of veteran posters feel?Perhaps the OP is not aware of the fact the Sun has a good deal of high quality study material published on their website. What's wrong with posting it in a thread? Why should one copy the same thing over and over again? If after reading that tutorial, the OP still has some questions about it, s/he is free to post a follow up question. I am sure that many of the regulars here are more than happy to answer them.
    Also note that the OP's problem description is rather vague. A "I don't know where to start" is IMO best answered by a link to a comprehensive tutorial or a beginners book.
    Being one of the (relatively) novice posters on the forum, I still feel the need to customize posts,Well, by all means: do so.
    trying to see things from the poster's side. Maybe after a few thousand posts, I'll just keep throwing the same documentation at newbies, instead of detailed customized responses, heh.IMO, that's a load of cr@p.

  • Plz need help with this hashmap program

    as far as i know, this hashmap program works, but i cant get it to compile correctly because of one line error:
    phoneArray[2] = int f;
    the second position in phoneArray is and will always be a number, but the array is a String array, making it difficult for me to take the number in that position and change it.
    In actuality, the number is a score (a grade) and i need to take it to change it to a letter grade, where it will later be spit out in order from Name, Year, Score, Grade.
    plz help, this is a school assignment and its driving me mad.
    import java.util.*;
    import java.io.*;
    * A class that represents a phone book.  This phone
    * book maps names to phone numbers.  This will
    * read teh phone book information from a file.
    public class CourseData2 {
      /////////////////// fields ///////////////////
      private String fileName;
      private Map phoneMap = new HashMap();
      /////////////////// constructors ///////////////////
       * Constructor that takes a file name and reads
       * in the names and phone numbers from a file.
       * @param file the name of the file to read
      public CourseData2(String file) {
        this.fileName = file;
        // Read the map information in form the file
        readInfoFromFile();
      } // constructor
      /////////////////// methods ///////////////////
       * Get the phone number for hte passed nam
       * @param name the name to look up in hte map
       * @return the phone number if found, else null
      public String getPhoneNumber(String name) {
        String phoneNumber = (String) phoneMap.get(name);
        return phoneNumber;
      } // method getPhoneNumber()
       * Method to read the phone information from a
       * file and use it to fill hte map
      public void readInfoFromFile() {
        String line = null;
        String[] phoneArray = null;
        try {
          // create the reader
          BufferedReader reader =
            new BufferedReader(new FileReader(fileName));
          // loop reading from the file
          while ((line = reader.readLine()) != null) {
            if (line.indexOf(":") >= 0) {
              phoneArray = line.split(":");
              phoneMap.put(phoneArray[0].trim(),
                           phoneArray[1].trim(),
                           phoneArray[2].trim());
            } // if
            } // while
            (int)phoneArray[2] = int f;
            if (f < 60) { (String)a = "E";}
            else if (60 <= f < 70) { (String)f = "D";}
            else if (70 <= f < 80) { (String)f = "C";}
            else if (70 <= f < 90) { (String)f = "B";}
            else if (90 <= f) { (String)a = "A";}
          // Close the reader
          reader.close();
        } // try
        catch (FileNotFoundException ex) {
          SimpleOutput.showError("Could not find the file \"" + fileName + "\".");
        } // catch
        catch (Exception ex) {
          ex.printStackTrace();
        } // catch
      } // method readInfoFromFile()
      public void printBook() {
        // Sort hashtable.
        Vector phoneVector = new Vector(phoneMap.keySet());
        Collections.sort(phoneVector);
        // Display (sorted) hashtable.
        for (Enumeration phoneEnumeration = phoneVector.elements(); phoneEnumeration.hasMoreElements();) {
          String key = (String)phoneEnumeration.nextElement();
          System.out.println("Name: " + key + ", Year: " + phoneMap.get(key) + ", Score: " + phoneMap.get(key) + ", Grade: " + phoneMap.get(key));
        } // for
      } // method printBook()
      /* main method for testing */
      public static void main(String[] args) {
        CourseData2 phoneBook = new CourseData2("scores12.txt");
        System.out.println(phoneBook.getPhoneNumber("Lee"));
        System.out.println(phoneBook.getPhoneNumber("Smith"));
        phoneBook.printBook();
      } // main()
    } // class

    after much time and editing, this is the revised coding:
    import java.util.*;
    import java.io.*;
    * A class that represents a class score book.  This
    * book maps names to scores and grades.  This will
    * read the names, scores and grade information from a file.
    public class CourseData2 {
      /////////////////// fields ///////////////////
      private String fileName;
      private Map phoneMap = new HashMap();
      /////////////////// constructors ///////////////////
       * Constructor that takes a file name and reads
       * in the names and phone numbers from a file.
       * @param file the name of the file to read
      public CourseData2(String file) {
        this.fileName = file;
        // Read the map information in form the file
        readInfoFromFile();
      } // constructor
      /////////////////// methods ///////////////////
       * Get the phone number for hte passed nam
       * @param name the name to look up in hte map
       * @return the phone number if found, else null
      public String getPhoneNumber(String name) {
        String phoneNumber = (String) phoneMap.get(name);
        return phoneNumber;
      } // method getPhoneNumber()
       * Method to read the phone information from a
       * file and use it to fill hte map
      public void readInfoFromFile() {
        String line = null;
        String[] phoneArray = null;
        String a = "";
        try {
          // create the reader
          BufferedReader reader =
            new BufferedReader(new FileReader(fileName));
          // loop reading from the file
          while ((line = reader.readLine()) != null) {
            while ((line = reader.readLine()) != null) {
            if (line.indexOf(":") >= 0) {
              phoneArray = line.split(":");
              int f = Integer.parseInt(phoneArray[2]);
              if (0 <= f && f <= 100) {
            if (0 <= f && f < 60) { a = "E";}
            else if (60 <= f && f < 70) { a = "D";}
            else if (70 <= f && f < 80) { a = "C";}
            else if (80 <= f && f < 90) { a = "B";}
            else if (90 <= f && f <= 100) { a = "A";}
              } // if f between 0 and 100
            else if ( f > 100 && f < 0 )  {
            SimpleOutput.showError("Score is not an integer");
            String g = new String();
            g = phoneArray[2];
              }//if < 0
            }// if (line.index....
            phoneMap.put(phoneArray[0].trim(),
                        (phoneArray[1].trim() + phoneArray[2].trim() + (String)a));
            } // while2
            } // while
          // Close the reader
          reader.close();
        } // try
        catch (FileNotFoundException ex) { 
          SimpleOutput.showError("Could not find the file \"" + fileName + "\".");
        } // catch
        catch (Exception ex) {
          ex.printStackTrace();
        } // catch
      } // method readInfoFromFile()
      public void printBook() {
        // Sort hashtable.
        Vector phoneVector = new Vector(phoneMap.keySet());
        Collections.sort(phoneVector);
        // Display (sorted) hashtable.
        for (Enumeration phoneEnumeration = phoneVector.elements(); phoneEnumeration.hasMoreElements();) {
          String key = (String)phoneEnumeration.nextElement();
          System.out.println("Name: " + key + ", Year: " + phoneMap.get(key) + ", Score: " + phoneMap.get(key) + ", Grade: " + phoneMap.get(key));
        } // for
      } // method printBook()
      /* main method for testing */
      public static void main(String[] args) {
        CourseData2 phoneBook = new CourseData2("scores12.txt");
        System.out.println(phoneBook.getPhoneNumber("Depp"));
          System.out.println(phoneBook.getPhoneNumber("Gonzales"));
            System.out.println(phoneBook.getPhoneNumber("Jenkins"));
                System.out.println(phoneBook.getPhoneNumber("Lee"));
                   System.out.println(phoneBook.getPhoneNumber("Mac Donald"));
                      System.out.println(phoneBook.getPhoneNumber("O'Malley"));
                         System.out.println(phoneBook.getPhoneNumber("Price"));
                            System.out.println(phoneBook.getPhoneNumber("Ramesh"));
                                System.out.println(phoneBook.getPhoneNumber("Smith"));
                                    System.out.println(phoneBook.getPhoneNumber("Winston"));
        phoneBook.printBook();
      } // main()
    } // classthis has no errors, but gives me 4 warnings, which i can't solve, plz help

  • I need help with my photoshop program. I need to talk to someone on the phone.

    I would like to talk to a support person on the phone about operating my photoshop program. It is not following commands properly!!

    @sbarabas:
    This is why I don't go online for help. You send me to another site when I have a job to do. Cannot go through this for two days. I would go broke.
    Well, you have to choose from one of the various options available for support to be able to talk to someone. Numbers are also region-specific. If you go in to this page http://helpx.adobe.com/contact/index.html you'll be able to drill down to what you want support for. You can get specific numbers there.
    I bought a new MacBook Pro and transfered everything from Time Machine. Now my Photoshop is not responding to my commands properly. It does what it wants to do and crashes when I move layers with the mouse.
    The answer to your issue is in your question itself. When you buy a new MacBook Pro and migrate data using Migration Assistant or Time Machine, Photoshop WILL misbehave. You have to do a fresh install of Photoshop using the installation disc or the downloaded installation file (if you opted for electronic delivery). This will 110% fix your issue.
    Please understand we're here to offer you solutions as well. We're not all Adobe employees, most of us are 'users' just like you who are voluntarily contributing to this community. We're more than willing to help you resolve this issue (just like we help 100s of users each day resolve their issues) if you're willing to provide us relevant and detailed information.
    Please feel free to post back with any other questions you may have.
    Regards,
    ST

  • I Need Help With Making This Program Work

    The directions for this program:
    Enhance the Student class to contain an Advisor. The advisor has a name (type Name), phone number (type String). Place edits in the Name class to validate that the length of the first name is between 1 and 15, middle inital <= 1, and lastName is between 1 and 15. Throw an IllegalArgumentException if the edits are not met. The advisor attribute in the Student class should replace the advisorName. Document the Name, Advisor, and Student classes including the preconditions and postconditions where necessary. Create a test class that will instantiate a Student, fully populate all of its fields and print it out. Do not document the test class. Submit for grade Student.java, Advisor.java, and Name.java.
    public class Student
         private Advisor advisorName;
         private Advisor phoneNumber;
         public void setAdvisorName(Advisor anAdvisorName)
             advisorName = anAdvisorName;
         public Advisor getAdvisorName()
             return advisorName;
         public void setPhoneNumber(Advisor aPhoneNumber)
             phoneNumber = aPhoneNumber;
         public Advisor getPhoneNumber()
             return phoneNumber;
    public class Name
         private String firstName;
         private String midInit;
         private String lastName;
         public String getFullName()
             return firstName + " " + midInit + " " + lastName;
         public String getFirstName()
             return firstName;
         public String getMidInit()
             return midInit;
         public String getLastName()
             return lastName;
            Calculates length of the first name.
            (Postcondition: getFirstName() >= 0)
            @param s the length of the first name to calculate
            (Precondition: length of aFirstName > 0 and <= 15)
         public void setFirstName(String aFirstName)
             if(aFirstName.length() < 1)
               throw new IllegalArgumentException();
             if(aFirstName.length() > 15)
               throw new IllegalArgumentException();
               firstName = aFirstName;
            Calculates length of the middle initial.
            (Postcondition: getMidInit() >= 0)
            @param s the length of the middle initial to calculate
            (Precondition: length of s > 0 and <= 1)
         public void setMidInit(String aMidInit)
             if(aMidInit.length() == 1)
               throw new IllegalArgumentException();
               midInit = aMidInit;
            Calculates length of the last name.
            (Postcondition: getLastName() >= 0)
            @param s the length of the last name to calculate
            (Precondition: length of aLastName > 0 and <= 15)
         public void setLastName(String aLastName)
             if(aLastName.length() < 1)
               throw new IllegalArgumentException();
             if(aLastName.length() > 15)
               throw new IllegalArgumentException();    
               lastName = aLastName;
    public class Advisor
         private Name advisorName;
         private String phoneNumber;
         public String getFullName()
            return advisorName + " " + phoneNumber + " ";
         public Name getAdvisorName()
             return advisorName;
         public String getPhoneNumber()
             return phoneNumber;
         public void setAdvisorName(Name anAdvisorName)
             advisorName = anAdvisorName;
         public void setPhoneNumber(String aPhoneNumber)
             phoneNumber = aPhoneNumber;
    public class Test
         public static void main(String[] args)
            Name name1 = new Name();
            name1.setFirstName("Timothy");
            name1.setLastName("O'Neal");
            name1.setMidInit("J.");
            System.out.println("name1 = " +
                name1.getFirstName() + " " +
                name1.getMidInit() + " " +
                name1.getLastName());
            Student st = new Student();
            st.setAdvisorName(name1);
            Name name2 = st.getAdvisorName();
            System.out.println("name2 = " +
                name2.getFirstName() + " " +
                name2.getMidInit() + " " +
                name2.getLastName());   
            name2.setFirstName("Timothy");
            System.out.println("name2 = " +
                name2.getFirstName() + " " +
                name2.getMidInit() + " " +
                name2.getLastName());       
            System.out.println("name1 = " +
                name1.getFirstName() + " " +
                name1.getMidInit() + " " +
                name1.getLastName());
            System.out.println("name1 = " + name1.getFullName());   
            System.out.println("name2 = " + name2.getFullName());
    }I can't get the test class to compile and i'm not sure if this is what i'm suppose to do

    public class Test
    public static void main(String[] args)
    Student st = new Student();
    Advisor advisor = new Advisor();
    st.setAdvisor(advisor);
    Name name1 = new Name();
    name1.setFirstName("Jake");
    name1.setLastName("Schmidt");
    name1.setMidInit("K.");You have the general idea, I think. You are just doing it backwards.
    You create and advisor and assign it to a student. But you don't give
    the advisor a name until after you assign it to the student.
    You should create an advisor, give the advisor a name and then add it to the student.
    //create the name
    Name name1 = new Name();
    name1.setFirstName("John");
    name1.setLastName("Smith");
    name1.setMidInit("K.");
    //create the advisor
    Advisor advisor = new Advisor();
    advisor.setAdvisorName(name1);
    //create the student
    Student student = new Student();
    //assign the advisor to the student
    student.setAdvisor(advisor);
    //now the student has an advisor named John K. Smith
    //What is the name of the advisor?
    String name = st.advisor.getAdvisorName().getFullName();
    //I know that line looks complicated...but that's how you have created your class structure.
    Instead you could have done:
    Class Student{
    private Advisor advisor;
    public String getAdvisorName(){
    return advisor.getFullName();
    class Advisor{
    private Name advisorName;
    public getFullName(){
    return advisorName.getFullName();
    This way, if you wanted to know the advisor's name you would go:
    String name = st.getAdvisorName();
    which is much easier.
    I think it would be much easier to help you if we were both in the same room, on the same computer :)

Maybe you are looking for

  • Multiple problems with syncing deleting media off iPhone

    The syncing process on the iPhone is very frustrating. As all know, with the iPod, if I wanted to put a song I had in iTunes onto my iPod, all I had to do was connect my iPod, click on the song in iTunes, and drag it on to my iPod. Easy. No more. Wit

  • What size external hard drive should I purchase

    What size external hard drive should I purchase?  I'm not tech savvy, so please speak slowly.  I'm looking at OWC Mini Stack Classic to match my  older Mac Mini.  Do I need 500 GB, 1 TB or more?      Plus, I have to add memory to upgrade to Snow Leop

  • No recovery possible after red_log 100000 and log_archive_format changing

    Hello Together, on a big production database (> 1TB, SAP-System) we passed the number 100000, so we was costrict to set log_archive_format explizit --> log_archive_format = %t_%s <--- Once a month we refresh a preproduction system (it is a job we kno

  • How to Host completed Captivate 5 Content

    I thought completed Captivate 5 Content could be hosted on Acrobat.com.  I see how to upload and share content for reviews.  I have attempted to upload a project and all that I see will upload is a zip and pdf file but not cptx.  I thought the option

  • Cropping non-rectangular image

    Hello, I need to crop  a slightly non-rectangular, four-sided image (a photo of a picture in a frame) and end up with a rectangular image. I've tried cropping and lassoing but nothing seems to do the job. Most grateful if anyone can tell me how I mig