Different classes problems

I posted a topic asking for feedback on a Vigenere Cipher program I made. It was said that I shouldn't have the entire program in one class, and should have different class... or methods?
I've been reading the tutorial for different classes, but I just can't seem to pick it up. I anticipate I'm gonna get a few replies with people saying 'you should read this smelly student' but I've tried, so I figure this may be a way to break me in :).
So, here's my code:
public class VigenereCipherComplete
     public static void main(String[] args)
     String key, message;
     String encrMessage = "";
     String[] options = new String[] {"Encrypter", "Decrypter", "Cancel"};
     int progChoice, keyLength, length, encrCharValue;
     int index;
     int keyIndex = 0;
     char keyChar;
     char messageChar;
     char encrChar;
     boolean shouldEncrypt = true;
     // Choice of whether to use the encrypter of decrypter
        progChoice = JOptionPane.showOptionDialog(null, "Which would you like to run?", "Program choice",
             JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
        if(progChoice == 0)
             shouldEncrypt = true;
        else if(progChoice == 1)
            shouldEncrypt = false;
    else
       System.exit(0);
     // Input of key and converting it to upper case
     key = JOptionPane.showInputDialog(null, "Please input the key you wish to use:",
          "Key input", JOptionPane.QUESTION_MESSAGE);
     key = key.toUpperCase();
     // Input of message and converting it to upper case
     message = JOptionPane.showInputDialog(null, "Please input the plaintext you wish to use:",
          "Plaintext input", JOptionPane.QUESTION_MESSAGE);
     message = message.toUpperCase();     
     keyLength = key.length();
     length = message.length();
     // Encryption/decryption
     for(index = 0; index < length; index++)
          keyChar = key.charAt(keyIndex);
          messageChar = message.charAt(index);
          if(messageChar >= 'A' && messageChar <= 'Z')
               // Encryption
               if(shouldEncrypt)     
                    encrCharValue = (keyChar - 'A') + messageChar;
               // Decryption
               else
                    if(messageChar >= keyChar)
                         encrCharValue = (messageChar + 'A') - keyChar;
                    else
                         encrCharValue = ((('Z' - keyChar) + messageChar) + 1);
               // Loops ascii char value larger than 90 so it stays within the 65-90 ascii char range
               if(encrCharValue > 'Z')
                    encrCharValue = (encrCharValue - 'Z') + 'A' - 1;
               // Converts the char value to a char and adds it to the converted string
               encrChar = (char)encrCharValue;
               encrMessage = encrMessage + encrChar;
               keyIndex++;     
          // If the char is not a letter, it leaves it as it is and adds it to the converted string     
          else
               encrCharValue = messageChar;
               encrChar = (char)encrCharValue;
               encrMessage = encrMessage + encrChar;
          // Resets key so it will loop for the full string wanting to be converted
          if (keyIndex >= keyLength)
               keyIndex = 0;
     // Output for encryption
     if(shouldEncrypt)
          System.out.println("Plaintext:\t" + message + "\nKey:\t\t" + key + "\nCiphertext:\t" + encrMessage);
     // Outfor for decryption
     else
          System.out.println("Ciphertext:\t" + message + "\nKey:\t\t" + key + "\nPlaintext:\t" + encrMessage);
}I just can't grasp how I'd do this... Sorry for the ambigious question.

I'm not going to read all your code. However, it's reasonable to put the code for one encryption algorithm into one class. If you were writing an entire encryption library, you might find that several of your algorithms (each in their own class) are all using the same code, and you're copying it from one class to another. In this case, you might extract that common code out to a utility class that various algorithms make use of.
Now, if we assume that your question is, "How can I break this code into smaller pieces?" here are a few suggestions, based on a cursory skimming of your code. Note that these are only guidelines, to give you an idea of the kinds of things that make sense to break out as pieces.
1. Keep the GUI separate from the encryption. You should have a VigenereEncryption or somesuch class that actually does the work of encrypting and decrypting, and this class should not know or care if there even is a GUI.
2. In the VE class, I would imagine you'd want an encrypt() method and a decrypt() method.
3. Anywhere you see multiple levels of nesting, one or more of those levels might be a candidate to pull out into its own method.
4. Anywhere you have repeated code that's more than a couple lines, put it in its own method.
5. Anywhere you have a comment like // perform such and such step above a block of code, that block is a good candidate to get pulled out into its own method, named similar to whatever that step is in your comments.
6. Similarly, when you learn what the high-level algorithm is that you're to be implementing, the steps of that algorithm are candidates to be their own methods.
Again, note that this is not carved in stone and is not meant to be taken literally as "do exactly all of these things." Rather, it is to give you ideas about the kinds of things that make for separation of classes and methods.

Similar Messages

  • Problem in importing two different classes with same name...

    I have to import two different classes in my program with the same name....
    import org.apache.lucene.document.Document;
    import org.w3c.dom.Document;
    //    I AM USING THE DOCUMENT FROM W3C PACKAGE HERE....
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                     DocumentBuilder builder = factory.newDocumentBuilder();
                     InputSource is = new InputSource( new StringReader( tempString ) );
                     d = builder.parse( is );
                     NodeList images = d.getElementsByTagName("img");
                     int length = images.getLength();
                     for(int i = 0;i<length;i++)
                         Node image = images.item(i);
                         String tempAltText = image.getAttributes().getNamedItem("alt").getNodeValue();
                         altText = altText.concat(" ").concat(tempAltText);
                     }and the error i am getting is
    [javac] C:\Documents and Settings\sumit-i\WolframWorkspaces\Base\WolframNutch\src\java\com\wolfram\nutch\indexer\InfoCenterFilter.java:20: org.apache.lucene.document.Document is already defined in a single-type import
        [javac] import org.w3c.dom.Document;
        [javac] ^
        [javac] C:\Documents and Settings\sumit-i\WolframWorkspaces\Base\WolframNutch\src\java\com\wolfram\nutch\indexer\InfoCenterFilter.java:132: incompatible types
        [javac] found   : org.w3c.dom.Document
        [javac] required: org.apache.lucene.document.Document
        [javac] d = builder.parse( is );
        [javac] ^
        [javac] C:\Documents and Settings\sumit-i\WolframWorkspaces\Base\WolframNutch\src\java\com\wolfram\nutch\indexer\InfoCenterFilter.java:133: cannot find symbol
        [javac] symbol  : method getElementsByTagName(java.lang.String)
        [javac] location: class org.apache.lucene.document.Document
        [javac] NodeList images = d.getElementsByTagName("img");
        [javac] ^
        [javac] Note: Some input files use unchecked or unsafe operations.
        [javac] Note: Recompile with -Xlint:unchecked for details.
        [javac] 3 errorsany idea ..how to resolve it
    Edited by: ping.sumit on Jul 16, 2008 3:39 PM
    Edited by: ping.sumit on Jul 16, 2008 3:40 PM

    now i changed the code to
    import org.apache.lucene.document.Document;
    import org.w3c.dom.Document;
    org.w3c.dom.Document d = null;
    try{
         System.out.println("in author");
                   URL url = new java.net.URL(urlString);
                   java.net.URLConnection conn = url.openConnection();
                   BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                   while ((in.readLine()) != null)
                        //tempString = tempString.concat(in.readLine());
                        String temp = in.readLine();
                        tempString = tempString + " " + temp;
                   System.out.println("the string in author" + tempString);
                    in.close();
                    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                     DocumentBuilder builder = factory.newDocumentBuilder();
                     InputSource is = new InputSource( new StringReader( tempString ) );
                     d = builder.parse( is );
                     NodeList images = d.getElementsByTagName("img");and their is only one error i am getting ...and that is
    [javac] C:\Documents and Settings\sumit-i\WolframWorkspaces\Base\WolframNutch\src\java\com\wolfram\nutch\indexer\InfoCenterFilter.java:20: org.apache.lucene.document.Document is already defined in a single-type import
        [javac] import org.w3c.dom.Document;
        [javac] ^
        [javac] Note: Some input files use unchecked or unsafe operations.
        [javac] Note: Recompile with -Xlint:unchecked for details.
        [javac] 1 error

  • Can't call or execute of different class files in a main program

    Hi, I got a main program which can call 3 different classes. The main program have an implicit-choice List as a starting menu. If one of the file is selected, the files will call out and display it. However, i managed to call the 1st 2 files, and the 3rd files can't display anything after selected.
    I enclosed my code as below:
    import javax.microedition.midlet.*;
    import javax.microedition.lcdui.*;
    public class Catalogues extends Form implements CommandListener {
         private Displayable parent;
         private Display display;
         private List Cata;
         private Boots bo;
         private Higheels hHeels;
         private Sandals sand;
         private Slippers sp;
        private Command backCommand = new Command("Back", Command.BACK, 1);
        private Command viewCommand = new Command("View", Command.SCREEN, 1);
        private String[] options = {"Boots", "High Heels","Sandals", "Slippers"};
         public Catalogues(Display d, Displayable p) {
              super("Welcome to Footwear World");
              Cata = new List("Select Option", List.IMPLICIT, options, null);
              display = d;
            parent = p;
              addCommand(backCommand);
              addCommand(viewCommand);
              setCommandListener(this);
         public void commandAction(Command c, Displayable d) {
         if(d==parent && c==List.SELECT_COMMAND){
              switch(parent.getSelectedIndex()){
                   case 0:
                           if(bo==null){
                              bo = new Boots(display,parent);
                             display.setCurrent(bo);
                              break;
                   case 1:
                           if(hHeels==null){
                              hHeels = new Higheels(display,parent);
                             display.setCurrent(hHeels);
                              break;
                   case 2:
                           if(sand==null){
                              sand = new Sandals(display,parent);
                             display.setCurrent(sand);
                              break;
                   case 3:
                           if(sp==null){
                              sp = new Slippers(display,parent);
                             display.setCurrent(sp);
                              break;
                   default:
             else if (c==backCommand) {
                       display.setCurrent(parent);
    }If the 3rd option is selected, i'll display above mentioned layout which contain a list to select too.
    After build this project on WToolkit. It shown an error message which is as below:
    Project settings saved
    Building "SelectCustest"
    C:\WTK22\apps\SelectCustest\src\Catalogues.java:29: cannot resolve symbol
    symbol : method getSelectedIndex ()
    location: class javax.microedition.lcdui.Displayable
    switch(parent.getSelectedIndex()){
    ^
    1 error
    com.sun.kvem.ktools.ExecutionException
    Build failed
    May i know what is problem am i facing now? And how to solve it.
    Thanks.

    Thanks to all for your thoughts and replies. I liked the xargs suggestion, so I tried that first. I would have (may still) try the stdin suggestion, followed by writing the grep output to a file.
    xargs does work, in a way I didn't expect it to, but that could be due to my inexperience with the workings of the shell.
    here's a line from my test script
    cat file | grep foo | xargs java com.company.test.TEchoArghere's the contents of 'file'
    123foo
    abc
    qafoozv
    qaz
    wsx
    qwefoort
    zxcfooh
    sdfghhere's the output from the test class, which just echos any arguments
    ::number of args: 4
    ::args[0] 123foo
    ::args[1] qafoozv
    ::args[2] qwefoort
    ::args[3] zxcfoohso xargs appends all the values from grep into an argument list and call the java class once.
    when I took xargs out of the script, nothing was passed to the class:
    ::number of args: 0this was really interesting and something to keep in my back pocket for future use.
    Thanks again to all.
    Tom

  • Accessing a different class using ActionPerformed

    hi
    im trying to access a method in a different class using
    public void actionPerformed (ActionEvent e) {
              if(e.getSource() == AuthorCombo) {
                   ComboAction();
              else if(e.getSource() == SearchButton){
                        SearchSystem();
    }and then using
    public class Book extends ViewPanel{
    public void SearchSystem(){// this is used to get the information from
                      //the combo boxs whixh can latter show
                      //the data in the text area
    tempBookNoList.clear();
              for(int a=0; a<AuthorList.size(); a++) {
                                  if(((String)AuthorCombo.getSelectedItem()
                                  ==AuthorList.get(a))
                                  &&((String)BookCombo.getSelectedItem()
                                  ==BookList.get(a))) {
                                       tempBookNoList.add((String)BookNoList.get(a));
                        String result = (String)tempBookNoList.get(a);
                        InfoArea.setText ((String)tempBookNoList.get(a));
    }          }//End neither random situation.to manipulate some data within the other class
    i keep getting the error
    .\ViewPanel.java:314: cannot resolve symbol
    symbol : method SearchSystem ()
    location: class ViewPanel
                        SearchSystem();
    ^
    1 error
    can anyone help me spot the problem

    in that case i do not know what could be the cause in this program
    the only area i think it could be is when the SearchSystem method in the Book class gets using the Action Performed method in the Viewpanel method, shown below
    public class Book extends ViewPanel{
    public void SearchSystem(){// this is used to get the information from
                      //the combo boxs whixh can latter show
                      //the data in the text area
              for(int a=0; a<AuthorList.size(); a++) {
                                  if(((String)AuthorCombo.getSelectedItem()
                                  ==AuthorList.get(a))
                                  &&((String)BookCombo.getSelectedItem()
                                  ==BookList.get(a))) {
                                  InfoArea.setText((String)BookNoList.get(a));
                   }which is called using
    public void actionPerformed (ActionEvent e) {
              if(e.getSource() == AuthorCombo) {
                   ComboAction();
              else if(e.getSource() == SearchButton){
                        theBook.SearchSystem();
    }but i cant see this being a problem as it all compiles

  • Refreshing AbstractTableModel from different class...

    Hi there ppl
    Anybody know how to call:
    model.fireTableStructureChanged()
    from a different class? when i try i get a compiler error saying that i cannot reference a non-static variable from a staic content.
    the first jframe holds a jtable that displays the model which consists of data from a db. the second jframe (which resides in another class) has a jtextfield which when submitted will update the db, therefore the db results need to be updated and then the model needs to be updated via
    model.fireTableStructureChanged()
    but from a different class. Is this possible and if so can somebody explain to me how?
    Thanks fellow Javites.

    Thanks for replying...
    The TrainServiceFrame.updateStationTable() exists within the TrainServiceFrame class and is intended to update the stationModel object when called from another class (which will be the NewTrainStationFrame class).
    <code>
         public static void updateStationTable() {
              stationModel.fireTableStructureChanged();          
    </code>
    The second code fragement is from the second class NewTrainStationFrame (which is not a subclass) which contains a jframe, jtextfield and a button. the method call to the stationModel(stationModel = AbstractTableModel) is done via: TrainServiceFrame.updateStationTable() when the submit button is clicked sending the string to a method ( addNewStation(newStation); )which updates the db.
    <code>
    button.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                        newStation = newStationField.getText();
                        addNewStation(newStation);
    // this would retrieve the updated db results + store in a TreeSet object
    // TrainServiceFrame.getTrainStations();
                        TrainServiceFrame.updateStationTable();
    </code>
    I have just noticed something that is missing which when attempted to fix resulted in the same problem. there should also be a method called to retrieve the updated db, but as this is from a static context yet again i fall into the same ditch as the variables that store these db results are non-static and exist within the TrainStationFrame class.
    Is the solution simply to change these relevent variables and methods that are to be called from another class, so that they are all static?

  • Sending text across different classes

    Okay, due to the nature of my rather large program, I've needed to institute a number of JTextAreas to do my debugging instead of System.out.print.
    The problem is, my applet invokes a number of different classes. Now, is there any simple way for a random object class to settext to a JTextArea in my applet class?
    I'm not sure if I'm describing this clearly so here' s a situation:
    public class myApplet extends javax.swing.JApplet {
    //within myApplet is a JTextArea named myDebugTA
    In a competely different class...
    public class myClass {
    //I would like to be able to settext to myDebugTA from this other class
    //is this easily possible?
    Now, I know I could always write the functions getDebugText() & setDebugText(), but that would be a REAL pain in the neck and a very time consuming solution given the size of my applet and the number of object classes.
    Is there any simple way to do this?
    Thanks in advance!
    Charles

    If I understand correctly, you can make a static method in myClass (you should name it MyClass BTW) and use a static text area. This is similar to the way System.out.println works.

  • BUG: OJC creates different classes than JAVAC making them incompatible

    Using the new JDeveloper 10g production release, I saw this behaviour when I used a class compiled in JDev (with OJC) passed over RMI to a server running classes compiled with in Ant (with JAVAC).
    I took the problematic class and stripped away parts of it until I have isolated the cause - seems related to class variable members initialization.
    I will provide several exapmles, where I used several modifications, giving the output of JAVAP for the same class, once compiled by JAVAC and once by OJC, highlighting the diff.
    Example #1:
    public class Test { static final int CONSTANT = 0; }JAVAC:
    Compiled from "Test.java"
    public class Test extends java.lang.Object{
        static final int CONSTANT;
        public Test();
    }OJC:
    Compiled from "Test.java"
    public class Test extends java.lang.Object{
        static final int CONSTANT;
        static {};
        public Test();
    Example #2:
    public class Test { final int CONSTANT = 0; }JAVAC:
    Compiled from "Test.java"
    public class Test extends java.lang.Object{
        final int CONSTANT;
        public Test();
    }OJC:
    Compiled from "Test.java"
    public class Test extends java.lang.Object{
        final int CONSTANT;
        void $init$();
        public Test();
    Example #3:
    public class Test { static int CONSTANT = 0; }JAVAC:
    Compiled from "Test.java"
    public class Test extends java.lang.Object{
        static int CONSTANT;
        public Test();
        static {};
    }OJC:
    Compiled from "Test.java"
    public class Test extends java.lang.Object{
        static int CONSTANT;
        static {};
        public Test();
    Example #4:
    public class Test { int CONSTANT = 0; }JAVAC:
    Compiled from "Test.java"
    public class Test extends java.lang.Object{
        int CONSTANT;
        public Test();
    }OJC:
    Compiled from "Test.java"
    public class Test extends java.lang.Object{
        int CONSTANT;
        void $init$();
        public Test();
    }I also have two examples where both compilers produce the same output for JAVAP:
    public class Test { static int CONSTANT; }
    public class Test { int CONSTANT; }I hope this is enough information to solve this.
    Classes compiled with OJC should not be incompatible with classes compiled with JAVAC with the same settings!
    Regards,
    Yaniv Kunda

    I'm sorry but I'm too busy with an urgent project to set up a RMI client/server testbed for this to test this problem, but all the example I gave are ones I've performed myself, and which all work - a simple class containing a constant (in several variations of its modifiers) compiled once with JAVAC and once with OJC produced different classes.
    I simply used javap to find out the difference between the classes, and highlighted the differences in bold - that would be a good place to start looking for the bug.
    Besides I'm not sure how to create a test that loads two versions of the same class not using RMI (perhaps via a special ClassLoader?)
    Regards,
    Yaniv Kunda

  • Updating Jlabel from a different class?

    Hi,
    Im in the middle of developing a program but swing is making it very hard for me to structure my code. The problem is I want to update the text of a Jlable from a different class when a button is pressed. THe event handling is done by a different class than the where the Jlabel is initiated which is why i think it doesnt work. But when the button is pressed it does execute a method from the main class that has the .setText() in it. Why wont the Jlabel update? Thank you

    Thanks for your help but i am still having trouble.
    This is the code from the button handler class
    public void actionPerformed(ActionEvent e)
           if ("btn3_sender".equals(e.getActionCommand()))
                JLabel j = temp2.getlblQuestion();
               j.setText("NEW TEXT");
           This is the code from the main class where the JLabel is created:
    public JLabel getlblQuestion()
        return lblQuestion;
    }How come this does not work??

  • Updating JPanel with buttons from a different class

    I have a JPanel in a class that has a gridlayout with buttons in it for a game board. And my problem is that when I want to update a button using setIcon() the button doesn't change in the GUI because the buttons are in a different class. The JPanel is in a Client class and the buttons are in a GamePlugin class. I've tried a bunch of different things but none of them worked or it was way too slow. I'm sure theres an easy way to do it that I'm not seeing. Any suggestions? Heres part of my code for updating the GUI.
    private JPanel boardPanel = new JPanel(); 
    Container cP = getContentPane();
    cP.add(boardPanel, BorderLayout.WEST);
    boardPanel.setPreferredSize(new Dimension(400, 400));
    boardPanel.setLayout(new GridLayout(8, 8));
    cP.add(optionsPanel, BorderLayout.CENTER);
          * Gets the board panel from the selected plugin.
         public void drawGameBoard(GamePlugin plugin) {
              board = (OthelloPlugin)plugin;
              boardPanel = board.getBoardPanel();
              for (int i = 0; i < GamePlugin.BOARD_SIZE; i++)
                   for (int j = 0; j < GamePlugin.BOARD_SIZE; j++) {
                        board.boardButtons[i][j].setActionCommand("" + i + "" + j);
                        board.boardButtons[i][j].addActionListener(this);
          * This method takes a GameBoard and uses it to update this class' data
          * and GUI representation of the board.
         public void updateBoard(GamePlugin updatedBoard) {
              board = (OthelloPlugin)updatedBoard;
              for (int i = 0; i < GamePlugin.BOARD_SIZE; i++) {
                   for (int j = 0; j < GamePlugin.BOARD_SIZE; j++) {
                        int cell = board.getCell(i,j);
                        if (cell == OthelloPlugin.PLAYER1){
                             board.boardButtons[i][j].setIcon(black);
                        else if (cell == OthelloPlugin.PLAYER2)
                             board.boardButtons[i][j].setIcon(white);
                        else
                             board.boardButtons[i][j].setText("");
         }

    txp200:
    I agree that a call to validate() , possibly repaint(), should fix your problem. In the class with the panel that the buttons are on, i would create a static repaint method that call panel.repaint(). You can then call that method in your other class. Just make sure u only use methods to change the properties of the button, never make a make a new one, as then you will lose the association with the panel. Hope this helps.
    -- Brady E

  • Help! -- different class loader issue

    From within an EJB I am trying to cast a serializable object, that was passed into this EJB, to its original type. The process ended with a ClassCastException, even though I have double checked that the object being casted is of the correct type and fully qualified package path. It turns out that the problem is caused by the involvment of 2 different class loaders -- The class loader that loads the object is not the same one that loads the EJB doing the casting. The thing that confuses me the most is that this program used to work fine without the exception when it was running in an older environment. Is this a VM issue? Do we have control over what class loader to use when load certain classes/objects? What's the fix to the problem?
    Please help!
    Thanks in advance.
    Lifeng

    It is a Java platform version issue. Since Java 2 The classloaders are lay out in a hierarchy. You can read about it in the public chapters of the book "Inside the Java 2 Virtual Machine" by Bill Venners at
    www.artima.com
    This may be helpful for you . It specifies the class loaders used by a thread to load subsequent classes: aThread.setContextClassLoader(aClassLoader)
    Other soulution is to have the object and EJB being loaded by the same class loader, which could be a common parent class loader for the ones that in your code are actually asked to load these objects
    Otherwise, java.lang.reflect can deal with objects whose type is not known by the compiler.

  • Two equal objects, but different classes?

    When programming on binding Referenceable object with JDK version 1.5.0_06, I have encountered a very strange phenomenon: two objects are equal, but they belong to different classes!!!
    The source codes of the program bind_ref.java are listed as below:
    +++++++++++++++++++++++++++++++++++++++++++++++++++++++
    import java.lang.*;
    import java.io.*;
    import java.util.*;
    import javax.naming.*;
    import javax.naming.spi.ObjectFactory;
    import java.util.Hashtable;
    public class bind_ref {
    public static void main( String[] args ) {
    // Set up environment for creating the initial context
    Hashtable env = new Hashtable();
    env.put( Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory" );
    env.put( Context.PROVIDER_URL, "file:/daniel/" );
    Context ctx = null;
    File f = null;
    Fruit fruit1 = null, fruit2 = null;
    byte [] b = new byte[10];
    try {
    ctx = new InitialContext( env );
    Hashtable the_env = ctx.getEnvironment();
    Object [] keys = the_env.keySet().toArray();
    int key_sz = keys.length;
    fruit1 = new Fruit( "Orange" );
         SubReference ref1 = fruit1.getReference();
    ctx.rebind( "reference", fruit1 );
         fruit2 = ( Fruit )ctx.lookup( "reference" );
         System.out.println( "ref1's class = (" + ref1.getClass().toString() + ")" );
         System.out.println( "fruit2.myRef's class = (" + fruit2.myRef.getClass().toString() + ")" );
         System.out.println( "( ref1 instanceof SubReference ) = " + ( ref1 instanceof SubReference ) );
         System.out.println( "( fruit2.myRef instanceof SubReference ) = " + ( fruit2.myRef instanceof SubReference ) );
         System.out.println( "ref1.hashCode = " + ref1.hashCode() + ", fruit2.myRef.hashCode = " + fruit2.myRef.hashCode() );
         System.out.println( "ref1.equals( fruit2.myRef ) = " + ref1.equals( fruit2.myRef ) );
    } catch( Exception ne ) {
    System.err.println( "Exception: " + ne.toString() );
    System.exit( -1 );
    +++++++++++++++++++++++++++++++++++++++++++++++++++++++
    All the outputs are shown as below:
    =======================================================
    Fruit: I am created at Mon Jun 18 11:35:13 GMT+08:00 2007
    SubReference: I am created at Mon Jun 18 11:35:13 GMT+08:00 2007
    --------- (i)subref.hashCode() = (-1759114666)
    SubReference: I am created at Mon Jun 18 11:35:13 GMT+08:00 2007
    --------- (i)subref.hashCode() = (-1759114666)
    FruitFactory: obj's class = (class javax.naming.Reference)
    FruitFactory: obj's hashCode = -1759114666
    FruitFactory: obj = (Reference Class Name: Fruit
    Type: fruit
    Content: Orange
    FruitFactory: ( obj instanceof SubReference ) = false
    FruitFactory: subref_class_name = (Fruit)
    Fruit: I am created at Mon Jun 18 11:35:13 GMT+08:00 2007
    ref1's class = (class SubReference)
    fruit2.myRef's class = (class javax.naming.Reference)
    ( ref1 instanceof SubReference ) = true
    ( fruit2.myRef instanceof SubReference ) = false
    ref1.hashCode = -1759114666, fruit2.myRef.hashCode = -1759114666
    ref1.equals( fruit2.myRef ) = true
    ========================================================
    I hightlight the critical codes and outputs related to the strangeness with bold texts.
    Who can tell me what happens? Is it really possible that two objects belonging to different classes are equal? If so, why that?

    It can also depend on how you implement the equals method.
    class Cat {
        String name;
        Cat(String n) {
            name = n;
    class Dog {
        String name;
        Dog(String n) {
            name = n;
        public boolean equals(Object o) {
            return name.equals(o.name);
        public static void main(String[] args) {
            Dog d = new Dog("Fred");
            Cat c = new Cat("Fred");
            System.out.println(d.equals(c));
    }

  • How to use the different class for each screen as well as function.

    Hi Experts,
    How to use the different class for each screen as well as function.
    With BestRegards,
    M.Thippa Reddy.

    Hi ThippaReddy,
    see this sample code
    Public Class ClsMenInBlack
    #Region "Declarations"
        'Class objects
        'UI and Di objects
        Dim objForm As SAPbouiCOM.Form
        'Variables
        Dim strQuery As String
    #End Region
    #Region "Methods"
        Private Function GeRate() As Double
                Return Double
        End Function
    #End Region
    Public Sub SBO_Appln_MenuEvent(ByRef pVal As SAPbouiCOM.MenuEvent, ByRef BubbleEvent As Boolean)
            If pVal.BeforeAction = True Then
                If pVal.MenuUID = "ENV_Menu_MIB" Then
                End If
            Else ' Before Action False
                End If
        End Sub
    #End Region
    End Class
    End Class
    Rgds
    Micheal
    Vasu Anna Regional Feeling a???? Just Kidding
    Edited by: micheal willis on Jul 27, 2009 5:49 PM
    Edited by: micheal willis on Jul 27, 2009 5:50 PM

  • Cycle Counting is not fetching All Items in Different Classes

    Hi All,
    My client has performed cycle counting. Ideally system has to fetech all the items in different classes. But in cycle counting listing report only able to fetch few items.
    Please let me know are we missing something ?
    And please let me know the significance of "Assign Items". How to put the same.
    Regards,
    John
    Edited by: 911765 on Mar 14, 2012 4:36 AM

    1) CC won't fetch all items in all classes.
    It will look at only those items that are present in the assign items screen.
    It will only consider those items which have cycle count enabled flag set to Yes in item master
    It will only consider those items that have a non-zero frequency for the ABC class of the item.
    It will only print those items that have some onhand if you run the CC to ignore zero onhand items.
    2) You can either manually add items to a CC in the assign items window.
    OR
    You can reinitialize or update the CC (by going to the 3rd tab on CC screen)
    Make sure that you have run ABC compilation so each item has a ABC class. You should also specify the frequency for each ABC class.
    Sandeep Gandhi

  • Invoke a method in one class from a different class

    I am working on a much larger project, but to keep this simple, I wrote out a little test that would convey the over all theory of the program.
    What I am doing is starting out with a 2 JFrames and a Class. When the program is launched, the first JFrame opens. In this JFrame is a label and a button. When the button is clicked, the second JFrame opens. This JFrame has a textField and a button. The user puts the text in the textField and presses the button. When the button is pushed, I want the text that was just put in the textField, to be displayed in the first JFrame's label. I am trying to invoke a method in the first JFrame from the second, but nothing happens. I have also tried making the Class extend from JFrame1 and invoke it from there, but no luck. So, how do I invoke a method in a class from a different class?
    JFrame1 (I omitted the layout part. I made this in Netbeans so its pretty long)
    public class NewJFrame1 extends javax.swing.JFrame {
         private NewClass1 nC = new NewClass1();
         /** Creates new form NewJFrame1 */
         public NewJFrame1() {
              initComponents();
              jLabel1.setText("Chuck");
         public void setLabels()
              jLabel1.setText(nC.getName());
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                                  
         NewJFrame2 j2 = new NewJFrame2();
         j2.setVisible(true);The class
    public class NewClass1 {
         public static String name;
         public NewClass1()
         public NewClass1(String n)
              name = n;
         public String getName()
              return name;
         public void setName(String n)
              name = n;
    }The second jFrame
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                                  
         NewClass1 nC = new NewClass1();
         NewJFrame1 nF = new NewJFrame1();     
         nC.setName(jTextField1.getText());
         nF.setLabels();
         System.out.println(nC.getName());At this point I am begging for help. I have been trying for days to figure this out, and I just feel like I am not getting anywhere.
    Thanks

    So, how do I invoke a method in a class from a different class?Demo:
    public class Main {
        public static void main(String [] args) {
         Test1 t1 = new Test1();
         Test2 t2 = new Test2();
         int i = t1.method1();
         String s = t2.method2(i);
         System.out.println(s);
    class Test1 {
        public int method1() {
         return 10;
    class Test2 {
        public String method2(int i) {
         if (i == 10)
             return "ten";
         else
             return "nothing";
    }Output is "ten".
    Edited by: newark on May 28, 2008 10:55 AM

  • How to call to another form declare in different class ???????

    hi, i'm beginner in j2me...
    I was wondering how to call to other form(class) in the current form...
    For example,
    public class A extends MIDlet implements CommandListener
    public void commandAction(Command d,Displayable s)
    if (d==*OKCommand*)
    if press this OK command, it will be able to show another form declared in the different class...
    How to make it able to call to other form/class(eg.classB)????
    public class B
    //form that will be shown after pressed command OK in class A
    please help if you know...Thanks a lot..... =)

    you MUST have a reference to the other class or MIDlet in the current MIDlet ...
    i think that i have answered to these kind of questions a few month ago.. you should use the 'search' engine to find the topic..
    CLDC and MIDP forum is not a huge forum compare to Java Programming forum so it will be easy !

Maybe you are looking for

  • I can't sync playlists from my iPod 5th gen to my iTunes library on new laptop

    I have a new laptop and have managed to move all my music to it and install iTunes and all the albums are correct and present, but it was a bit complicated. I'm not sure if we missed a step in moving everything via a larger hard drive, but my playlis

  • Error message on "Sharing" Project

    A recently made Project that was easily exported: Share->Media Browser->HD 720. So I know I can do this and have done it may times in the past. However if I go back and work (retool) on a project from say a couple years ago, and I try same exporting

  • Error not displaying while Invoice Apprvoal in detail tab

    Hi, Here is the problem we are facing. We are at SRM 5.0 with Extended Classic and no IMS configured. u2022 Activity u2013 1. Invoice with value more than PO value is posted and triggered for approval. Zero Tolerance  maintained. 2. Posted Invoice ha

  • Open c won't turn on

    my zte open c died today. Battery was 1/3, and i plugged it into car charger, and it went blank, and is now unresponsive in every way, its not "bricked" it is a brick. i had the zte open for about 5months and it went the same way, except in that case

  • Problem in recreating control file

    Hi, When i recreate controlfile ... It creates a set of datafile... FILE# NAME STATUS 84 /u01/app/oracle/product/10.2.0/dbs/MISSING00084 RECOVER 85 /u01/app/oracle/product/10.2.0/dbs/MISSING00085 RECOVER 86 /u01/app/oracle/product/10.2.0/dbs/MISSING0