Calling another class file

I am trying to write an app to that calls another class file but i keep getting this error:
"Message.java": Error #: 300 : class Attachment not found in class Message at line 229, column 37
And this is the code where i am getting this error:
public final void addAttachment(Attachment attachment)
attachments.add(attachment);
Can someone tell me what i am doing wrong or how to fix this?
Thank you.

This query brings up another point that is unrelated but of interest to me. Take a look at that method, addAttachment. All it does is call add(attachment) on an object variable that's not even lexically scoped. Is there really any benefit, any savings whatsoever in readability or ease of programming etc. in having that method? As it stands, I tend to view it as an exercise in typing. I see this a lot and so I wonder if it's just a Java thing or what.

Similar Messages

  • How can we call a class file of one package for class file of another

    How can we call a class file of one package from class file of another package and both packages exist in a same folder

    How can we call a class file of one package from
    class file of another package and both packages exist
    in a same folder
    Luckily they don't so it's really not a problem after all.

  • One Class Calling Another Class ......Need Help..ugh

    this is the class that calls another class called cuboid
    package WindowsApplication1;
    * Summary description for Cuboid.
    //Import the classes to allow the use of the array, iterator and listiterator
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.ListIterator;
    public class DisplayCuboidValues
         public static void main(String args[])
              //Create the array list
              ArrayList VolumeList = new ArrayList();
              //Create the counter to loop 4 times and get 4 different volumes. Modify the counter
              //if you need a different values
              int Counter = 1;
              //Initialize the counter to loop 4 times in order to get the 4 objects
              while (Counter < 5)
                   Cuboid mp = new Cuboid(2, 4, 3);
                   //Add the values to the array
                   VolumeList.add(mp);
                   // get the volume again via accessor method(Optional)
                   //int Volume = mp.Volume();
                   //System.out.println(Volume);
                   //Increment the counter to obtain a new value in the array
                   Counter = Counter + 1;
              // Retrieve iterator to the radiuslist
              Iterator itr1 = VolumeList.iterator();
              while (itr1.hasNext())
              // call Cuboid.toString()
              System.out.print(itr1.next());
              System.out.println();
    }this is the cuboid class
    package WindowsApplication1;
    * Summary description for Cuboid.
    public class Cuboid
         private final int length, width, height;
         //1st contructor with 3 arguments
         public Cuboid(int length, int width, int height)
              this.length = length;
              this.width = width;
              this.height = height;
         //2nd constructor with no arguments
    //I BELIEVE THIS PUBLIC CUBOID IS THE ONE THE PROVOKES THE ERROR. BUT I CAN NOT DELETE IT BECAUSE I NEED ANOTHER PUBLIC CUBOID. SO IDK WHAT TO DO......
         public Cuboid()
              this.length = length;
              this.width = width;
              this.height = height;
            public String toString() {
                   return "This cuboid has length x, width y, height z, and has volume of v where X=" + length + " " + "Y=" + width + " " + "Z=" + height + " " + "Volume=" + length * width * height + ".   --   ";
         //Method to calculate the Volume
         public int Volume()
              return length * width * height;
         }This is what i have done. I have created a project named ths(which i do not use it at all). Then, i created one file called DisplayCuboidValues under ths. Then i created the file Cuboid under ths too. But it gives me errors. like this one:
    init:
    deps-jar:
    Created dir: C:\Documents and Settings\Owner\ths\build\classes
    Compiling 1 source file to C:\Documents and Settings\Owner\ths\build\classes
    C:\Documents and Settings\Owner\ths\src\DisplayCuboidValues\Cuboid.java:25: variable length might not have been initialized
    this.length = length;
    *^*
    C:\Documents and Settings\Owner\ths\src\DisplayCuboidValues\Cuboid.java:26: variable width might not have been initialized
    this.width = width;
    *^*
    C:\Documents and Settings\Owner\ths\src\DisplayCuboidValues\Cuboid.java:27: variable height might not have been initialized
    this.height = height;
    *^*
    Note: C:\Documents and Settings\Owner\ths\src\DisplayCuboidValues\DisplayCuboidValues.java uses unchecked or unsafe operations.
    Note: Recompile with -Xlint:unchecked for details.
    *3 errors*
    BUILD FAILED (total time: 0 seconds)
    Any help you can give me will be appreciated. Thanks.

    yeah. you are right in that. so that means that i have to get rid of it??. because i will need it. and the values assigned to them is in the first class that calls the second class look:
    package WindowsApplication1;
    * Summary description for Cuboid.
    //Import the classes to allow the use of the array, iterator and listiterator
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.ListIterator;
    public class DisplayCuboidValues
         public static void main(String args[])
              //Create the array list
              ArrayList VolumeList = new ArrayList();
              //Create the counter to loop 4 times and get 4 different volumes. Modify the counter
              //if you need a different values
              int Counter = 1;
              //Initialize the counter to loop 4 times in order to get the 4 objects
              while (Counter < 5)
    *//HERE IS WHERE I AM PROVIDING THE OTHER CLASS WITH VALUES. THEREFORE IT SHOULD SENT THOSE VALUES TO MY CLASS CUBOID AND RETRIEVE THE ANSWER TO FOLLOW THE REST OF THIS CODE.*
                   Cuboid mp = new Cuboid(2, 4, 3);
                   //Add the values to the array
                   VolumeList.add(mp);
                   // get the volume again via accessor method(Optional)
                   //int Volume = mp.Volume();
                   //System.out.println(Volume);
                   //Increment the counter to obtain a new value in the array
                   Counter = Counter + 1;
              // Retrieve iterator to the radiuslist
              Iterator itr1 = VolumeList.iterator();
              while (itr1.hasNext())
              // call Cuboid.toString()
              System.out.print(itr1.next());
              System.out.println();
    }

  • Compiling a class calling another class

    Hi,
    I have a problem with running an applet.
    my applet contains a thread and calls another class.
    when i compile it with javac, it says "cannot resolve symbol class Compute" which is the name of the other class.
    thank you for your help.

    Hi friend,
    How you solved this problem? can u please explain me
    too...
    I've an error while compiling my java file. cannot
    resolve symbol : class Student.
    where my two java files are...
    StudentBean.java
    public class StudentBean
    public static void main(String args[])
    Student s = new Student();
    Student.java
    public class Student
    String id,name;
    public Student(String id,String name)
    this.id = id;
    this.name = name;
    Both are in the same folder, please help me out of it.
    Thanking you,
    Harshavardhan.I do not know about the symbol resolution. But you do not have a default constructor in Student which may be causing an issue with the compile.

  • How to call a class file in a jsp without deploying anything in j2ee

    Hi,
    I am new in J2EE. I have some jsps, which I configured using web.properties(documentroot=c:/jsp/). I am able to get
    those pages by the web browser. I have some import statements in some jsps, now I
    am trying to access those page but it is failing, it says
    org.apache.jasper.JasperException: Unable to compile class for
    JSPD:\j2sdkee1.3\repository\pradip\web\_0002fLogin_0002ejspLogin_jsp_0.java:1:
    Class com.gui.UPMGuiGlobalConstants not found in import.
    import com.gui.UPMGuiGlobalConstants;
    Actually I have not deployed any class file or jsps.. Now my question is can I access
    these jsps without deploying anything, like can I put my .jar file in any j2ee
    directory(like lib or anywhere else, I already tried after putting in /lib) and restart the
    j2ee and use it. So how can I call a class file from a jsp without any kind of
    deployment?
    Please send me the reply as soon as possible.
    Regds,
    Pradip

    After you put the jar containing the class to import into the WEB-INF/lib directory, you still need to include it in the jsp.
    Putting the jar into the lib dir, will make it available to the vm, but as in any other java class, you still need to import it into the class, that the jsp will be compiled into.
    And you do that by putting
    <%@page import="com.gui.UPMGuiGlobalConstants" %>somewhere near the top of your jsp. (well you don't need to put it there, but it good style ;)
    That should do it.

  • How can i call java class file in jsp page

    Hai,
    i wants to call .class file in jsp page.
    my class file is in C:\jsdk\bin.
    Thanks

    I'm not entirely sure what you mean by "calling a class file", but I'm going to assume that you want to do something like the following in your page:
    <%
    MyClass myClass = new MyClass();
    myClass.someMethod();
    %>etc
    If that's the case, then all you have to do is make sure that the class is in the servlet engine's classpath. You'll probably also need to include an appropriate import statement at the top of the page.
    Hope that helps.

  • How do I call a class file in my code?

    Hi,
    I have defined a class, 'WFLTrigger', in a file named WFLTrigger.java. I need to call a method of another class, 'importFile', from within the 'WFLTrigger' class. The 'importFile' class is hard-coded in another file named importFile.java.
    The following is the code snippet I use in the 'WFLTrigger' class to call the 'importFileMethod' method of the 'importFile' class.
    importFile impF = new importFile();
    impF.importFileMethod( clientX, session, "0b0007d58001c142", theFile );
    But, while compiling, I am getting an error:
    cannot find symbol.
    symbol : method importFile()
    location: class WFLtrigger
    importFile( clientX, session, "0b0007d58001c142", theFile );
    1 error
    Can anybody help me out here as to what is going wrong?
    Thanks,
    Arun

    Hi Paul,
    Thanks for the reply. In fact, I initially had the line of code:
    importFile( clientX, session, "0b0007d58001c142", theFile );
    Then I changed it to the snippet that I posted. I am using NetBeans 4.0 IDE on Windows 2000 SP4 OS.
    I am posting my entire code below:
    import com.documentum.fc.client.*;
    import com.documentum.fc.common.*;
    import com.documentum.com.*;
    import com.documentum.operations.*;
    import com.documentum.fc.client.IDfSysObject;
    import com.documentum.fc.client.IDfType;
    import com.documentum.fc.common.DfId;
    import java.util.* ;
    import java.lang.Integer;
    public class WFLtrigger
    public WFLtrigger(String[] args)
    IDfClientX clientX = new DfClientX();
    IDfClient client = DfClient.getLocalClient();
    IDfSessionManager sMgr = client.newSessionManager();
    IDfLoginInfo loginInfo = new DfLoginInfo();
    loginInfo.setUser("abc");
    loginInfo.setPassword("xyz");
    loginInfo.setDomain("");
    sMgr.setIdentity( "pqr", loginInfo );
    IDfSession session = sMgr.getSession( "pqr" );
    IDfFile theFile = clientX.getFile( "C:\\wet" );
    importFile impF = new importFile();
    impF.importFileMethod( clientX, session, "0b0007d58001c142", theFile );
    NetBeans does not compile it. It gives an error as stated in the post above at the 2nd last line.
    I appreciate any help on this.
    Thanks,
    Arun

  • Calling another java file

    I have a main class ( packet.java for example) and I need to call another file (filter.java) to display a dialog box. Both files are in the same package, but all I want to do is when a button is clicked in packet.java, I want it to display the dialog box in filter.java.

    example:
    you have to source files with one class in each:
    file1:
    public class HelloWorld {
       private String helloText = null;
       public HelloWorld(String text) { // constructor
          helloText = text;
       public String getMessage() {
          return "Hello " + helloText;
    }file2 (which accesses the class in file1):
    public class Foo {
       public static void main(String[] args)  {
          for(int i=0; i<args.length; i++) {
             HelloWorld hello = new HelloWorld(args);
    System.out.println(hello.getMessage());
    if you run the app like this:
    java Foo blackieul Thofthe output will be:
    Hello blackieul
    Hello ThofPlease specify your problem more detailed - e.g. post an exception message or the fragment of code where you don't know what to do...

  • How to call java class file from jsp

    hi
    we need to call java classes (which are written separately in .java file )from jsp file. we need it for our project if anyone knows about please reply us.
    bye
    siva sankari

    you can call the methods in a lot of ways. you could use scriptlets with the
    <%@ page import="package.class"%> and then inside instantiate an object
    <%
         MyClass mc = new MyClass(parameters if any);
         mc.theMethodYouWantToCall();
    %>or as Madathil has stated,
    or use the JSP tags
    <jsp:useBean id="anyname" class="classname"/>and then use the getProperty tag
    or even Custom Tags

  • Call java class file into jsp file

    Hello experts,
    I wrote a class file which have validation functions it successfully created a class file of that java file.
    and I puted that class file into tomcat's ../WEB-INF/classes folder.
    And whenever I am going to execute the jsp page it give error like
    "regexFunctions cannot be resolved to a type"
    My class file is like follows,
    import java.util.regex.*;
        public class regexFunctions
        private static int SUCCESS = 0;
        private static int FAILURE = 1;
        private static int MISSING_INFO = -1;
        public static String ALL_STRING_REGEX = "^[a-zA-Z]+$";
        public static String ALL_NUMBER_REGEX = "[0-9]+";
    public static int checkForString(String inputtedValue)
             int retCode = FAILURE;
             if ((inputtedValue != null) && (inputtedValue.length() > 0))
                 Pattern pattern = Pattern.compile(ALL_STRING_REGEX);
                 Matcher matcher = pattern.matcher(inputtedValue);
                 if (matcher.find())
                     retCode = SUCCESS;
             return retCode;
    }My jsp page is like follows,
                <%
                     regexFunctions reg = new regexFunctions();
         String id = request.getParameter("txtId");
         int i = regexFunctions.checkForString(id);
               %>So Please Let Me Help Out...

    Put it into a package. Classes in packages can't access classes with no package, since about 2003.

  • How to call another class function in SharePoint?

    Facing 'ConvertViewToHtml' does not exit in current context. Here is my code:
    namespace ChangeControl3_Nov
    class eGA_Utility
    public static void SendmailwithTwo(string To, string subject, string Body, string frommail, byte[] docFile, byte[] docFile1, string fileName1, string fileName3)
    string smtpServer = SPAdministrationWebApplication.Local.OutboundMailServiceInstance.Server.Address;
    string smtpFrom = SPAdministrationWebApplication.Local.OutboundMailSenderAddress;
    string smtpReplyTo = SPAdministrationWebApplication.Local.OutboundMailReplyToAddress;
    MailMessage mailMessage = new MailMessage();
    System.Net.Mail.MailAddress from = new System.Net.Mail.MailAddress(frommail, "Quality Management");
    mailMessage.From = from;
    mailMessage.To.Add(new MailAddress(To));
    mailMessage.Subject = subject;
    mailMessage.IsBodyHtml = true;
    mailMessage.Priority = MailPriority.High;
    mailMessage.Body = ConvertViewToHtml();
    MemoryStream stream = new MemoryStream(docFile);
    string fileName2 = fileName1;
    Attachment attachment = new Attachment(stream, fileName2);
    mailMessage.Attachments.Add(attachment);
    MemoryStream stream1 = new MemoryStream(docFile1);
    string fileName4 = fileName3;
    Attachment attachment1 = new Attachment(stream1, fileName4);
    mailMessage.Attachments.Add(attachment1);
    SmtpClient smtpClient = new SmtpClient(smtpServer);
    NetworkCredential oCredential = new NetworkCredential("", "");
    try
    smtpClient.UseDefaultCredentials = false;
    smtpClient.Credentials = oCredential;
    smtpClient.Send(mailMessage);
    catch (Exception)
    I would like to call "ConvertViewToHtml()" from FormCode.cs in this line: 
    mailMessage.Body = ConvertViewToHtml();
    namespace ChangeControl3_Nov
    public partial class FormCode
    public string ConvertViewToHtml()
    try
    byte[] sourceFile = null;
    XPathNavigator root = MainDataSource.CreateNavigator();
    string myViewName = this.CurrentView.ViewInfo.Name.Replace(" ", string.Empty);
    string myViewXslFile = myViewName + ".xsl";
    // Create the xsl transformer
    XslCompiledTransform transform = new XslCompiledTransform();
    transform.Load(ExtractFromPackage(myViewXslFile));
    // Generate a temporary HTML file
    string fileName = Guid.NewGuid().ToString() + ".htm";
    string filePath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), fileName);
    using (XmlWriter writer = XmlWriter.Create(filePath))
    // Convert the XML to HTML
    transform.Transform(root, writer);
    writer.Close();
    // Return the HTML as a string
    sourceFile = File.ReadAllBytes(filePath);
    return System.Text.Encoding.UTF8.GetString(sourceFile);
    catch (Exception ex)
    return "<html><body>Unable to convert the view to HTML <p>" + ex.Message + "</p></body></html>";
    How to do this? Thanks in advance!

    Hi Sam,
    According to your description, you might want to call a function from other class.
    Before calling this function, it will require to initialize a FormCode object and then we can call the functions of the FormCode class.
    You can take a look at the code snippet provided by tompsonn in this similar thread:
    http://www.overclock.net/t/1411342/calling-a-function-from-another-form-c
    More information about working with Partial Classes and Methods:
    http://msdn.microsoft.com/en-us/library/wa80x488.aspx
    Thanks 

  • Setting JTree in one class file from another class file

    Hello,
    I'm new to java. I recently created a project in netbeans and here is one of the java files. I used the IDE to make a split pane, with a tree structure and panel in it.
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    * AmplifierDesignGUI.java
    * Created on Jun 20, 2010, 1:18:52 PM
    package AmplifierDesign;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    * @author Bugz
    public class AmplifierDesignGUI extends javax.swing.JFrame {
    /** Creates new form AmplifierDesignGUI */
    public AmplifierDesignGUI() {
    initComponents();
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {
    jSplitPane1 = new javax.swing.JSplitPane();
    jScrollPane1 = new javax.swing.JScrollPane();
    jTree1 = new javax.swing.JTree();
    jPanel1 = new javax.swing.JPanel();
    jMenuBar1 = new javax.swing.JMenuBar();
    jMenu1 = new javax.swing.JMenu();
    jMenu2 = new javax.swing.JMenu();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    jScrollPane1.setViewportView(jTree1);
    jSplitPane1.setLeftComponent(jScrollPane1);
    org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
    jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    .add(0, 475, Short.MAX_VALUE)
    jPanel1Layout.setVerticalGroup(
    jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    .add(0, 274, Short.MAX_VALUE)
    jSplitPane1.setRightComponent(jPanel1);
    jMenu1.setText("File");
    jMenuBar1.add(jMenu1);
    jMenu2.setText("Edit");
    jMenuBar1.add(jMenu2);
    setJMenuBar(jMenuBar1);
    org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    .add(layout.createSequentialGroup()
    .add(8, 8, 8)
    .add(jSplitPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 571, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    .addContainerGap(32, Short.MAX_VALUE))
    layout.setVerticalGroup(
    layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    .add(layout.createSequentialGroup()
    .add(8, 8, 8)
    .add(jSplitPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 278, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    pack();
    }// </editor-fold>
    * @param args the command line arguments
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new AmplifierDesignGUI().setVisible(true);
    try {
    new JTreeStructure().setVisible(true);
    } catch (Exception ex) {
    Logger.getLogger(AmplifierDesignGUI.class.getName()).log(Level.SEVERE, null, ex);
    // Variables declaration - do not modify
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JTree jTree1;
    // End of variables declaration
    So once this was done I wanted to link the JTree to a mysql database. So I found a sample .java file on the net:
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package AmplifierDesign;
    import java.awt.*;
    import java.sql.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    public class JTreeStructure extends JFrame {
    Connection con = null;
    Statement st = null;
    ResultSet rs = null;
    //public static void main(String args[]) throws Exception {
    // new JTreeStructure();
    public JTreeStructure() throws Exception {
    super("Retrieving data from database ");
    String driver = "com.mysql.jdbc.Driver";
    String url = "jdbc:mysql://localhost:8889/";
    String db = "icons";
    ArrayList list = new ArrayList();
    list.add("Laser Objects");
    Class.forName(driver);
    con = DriverManager.getConnection(url + db, "root", "root");
    try {
    String sql = "Select * from fiberComponents";
    st = con.createStatement();
    rs = st.executeQuery(sql);
    while (rs.next()) {
    Object value[] = {"Fiber Components",rs.getString(2) };
    list.add(value);
    } catch (Exception e) {
    System.out.println(e);
    rs.close();
    st.close();
    con.close();
    Object hierarchy[] = list.toArray();
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container content = getContentPane();
    DefaultMutableTreeNode root = processHierarchy(hierarchy);
    JTree tree = new JTree(root);
    content.add(new JScrollPane(tree), BorderLayout.CENTER);
    setSize(275, 300);
    setLocation(300, 100);
    setVisible(true);
    private DefaultMutableTreeNode processHierarchy(Object[] hierarchy) {
    DefaultMutableTreeNode node = new DefaultMutableTreeNode(hierarchy[0]);
    DefaultMutableTreeNode child;
    for (int i = 1; i < hierarchy.length; i++) {
    Object nodeSpecifier = hierarchy;
    if (nodeSpecifier instanceof Object[]) // Ie node with children
    child = processHierarchy((Object[]) nodeSpecifier);
    } else {
    child = new DefaultMutableTreeNode(nodeSpecifier); // Ie Leaf
    node.add(child);
    return (node);
    The problem is when I run my program two windows open up. The original one with JTree1, and the panel and horizontal splitplane and another window with a new tree component that did get its objects from the database. My question is how do I "replace" the JTree1 with the new tree created from the second java file?
    Or additionally, maybe I could set the data for JTree1 from within the second java file?

    zmoddynamics wrote:
    ....Please excuse my post as I am not sure what is meant by code tags?To use code tags, highlight your pasted code (please be sure that it is already formatted when you paste it into the forum; the code tags don't magically format unformatted code) and then press the code button, and your code will have tags.
    Another way to do this is to manually place the tags into your code by placing the tag [cod&#101;] above your pasted code and the tag [cod&#101;] below your pasted code like so:
    [cod&#101;]
      // your code goes here
      // notice how the top and bottom tags are different
    [/cod&#101;]Luck.

  • How do I call another exe file from a Java program?

    Hi,
    I am doing a simple IDE (text editor/interpreter) for a simple programming language we are developing. It will be submitted as our project for this semester. I created an exe file (in C) which will be used as the interpreter. How do I call the interpreter from my IDE? The interpreter should run when the user clicks a button (i.e. the "Run" button). I've tried the Java Runtime class but it doesn't work. Anyone who knows how to do it?
    Thanks!

    I first tried to do a simple program that calls system commands such as dir, cd <dir>, etc.
    I do not have the exact code right now but as far as I can remember, here's what I wrote:
    class Sample{
        public static void main(String args[]) throws IOException{
           BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
           String command;
           while ((command = in.readLine()).equalsIgnoreCase("exit") == false){
              try{
                Runtime.getRuntime().exec(command);
              }catch(Exception e){
                 System.err.println("Error: " + e);
          System.exit(0);
    }

  • Calling another class's method

    I realize this is a basic question but I am stumped. I am updating existing code so do not have total freedom. To make my situation simple, I have two classes, say, ComplexDialog1 and ComplexDialog2. Each has a Checkbox. I need to know the States of both Checkboxes from either class. How do I do that? Since these classes are dialogs, I cannot simply instantiate another dialog to gain access to its methods. I thought about casting, something like, (ComplexDialog2)getCheckboxState, (where getCheckBoxState consists of checkbox.getState), but of course that won't compile. A global variable would be great, but those don't exist in Java. Any serious answers will be appreciated.

    know-nothing wrote:
    I realize this is a basic question but I am stumped. I am updating existing code so do not have total freedom. To make my situation simple, I have two classes, say, ComplexDialog1 and ComplexDialog2. Each has a Checkbox. I need to know the States of both Checkboxes from either class. How do I do that? Since these classes are dialogs, I cannot simply instantiate another dialog to gain access to its methods. At any rate this is where the design problem really is. It seems the state of your application is residing partially at least in these GUI classes. Which is wrong. The GUI is for display not for the logic and storing of state of the application. For more on this you should learn about MVC http://en.wikipedia.org/wiki/Model-view-controller
    So how are you going to solve this problem?
    Well the long and probably verbotten way is to fix the design.
    The shorter, possibly (and only in the short term because in the long term the bad design will cost you dearly when it comes to making changes and maintaining this application) allowed method is that you are going to have to have instances of both Dialogs available at the same time in your application. Now as you said they are dialogs so you can't display them both at the same time but you need to display them both. You only need to have them both in existence and then show and hide them as desired.
    This is going to take some code tweaking both inside these classes and with other classes as well. You have no choice in this matter. If you cannot change calling classes then you'll have to give up because it's hopeless.
    You must be able to access one instance from the other (and vice versa) perhaps through the parent class. I don't know what works best for you.

  • Need help writing application to call another class

    Hello All, this is only the second program I have ever written and I am lost. I am supposed to write one application that will encrypt a four digit number by 1st replacing each diigt with the result of adding 7, then getting the remainder after dividing by 10. Then swap the 1st and 3rd digits and the 2nd and 4th digits. Then print that number. I have that as follows:
    import java.util.Scanner;
    public class CH4_37_Encrypt
         public static void main( String[] args )
              // read in the 4 digit integer
              Scanner input = new Scanner(System.in);
              int number = input.nextInt();
              // parse the integer to the individual digits
              int thousands = number / 1000;
              number -= thousands * 1000;
              int hundreds = number / 100;
              number -= hundreds * 100;
              int tens = number / 10;
              number -= tens * 10;
              int ones = number;
              number -= ones;
              // output the original digits
              System.out.print("" + thousands + hundreds + tens + ones + "");
              // do the encryption
              // add 7 to each digit
              thousands += 7;
              hundreds += 7;
              tens += 7;
              ones += 7;
              // mod each digit by ten
              thousands %=10;
              hundreds %=10;
              tens %=10;
              ones %=10;
              // swap the 1st (thousands) and 3rd (tens) digits
              int temp = thousands;
              thousands = tens;
              tens = temp;
              // swap the 2nd and the 4th digit
              int temp1 = hundreds;
              hundreds = ones;
              ones = temp1;
              // output the encrypted integer
              System.out.printf("%d", number);
    Next, I am to write a seperate application that inputs an encrypted four digit number and decrypts it to form the original number. I am a little confused how to go about this. Thanks in advance!!!

    Hello All, this is only the second program I have
    ever written and I am lost. I am supposed to write
    one application that will encrypt a four digit number
    by 1st replacing each diigt with the result of adding
    7, then getting the remainder after dividing by 10.
    Then swap the 1st and 3rd digits and the 2nd and 4th
    digits. Then print that number. I have that as
    follows:
    import java.util.Scanner;
    public class CH4_37_Encrypt
         public static void main( String[] args )
              // read in the 4 digit integer
              Scanner input = new Scanner(System.in);
              int number = input.nextInt();
              // parse the integer to the individual digits
              int thousands = number / 1000;
              number -= thousands * 1000;
              int hundreds = number / 100;
              number -= hundreds * 100;
              int tens = number / 10;
              number -= tens * 10;
              int ones = number;
              number -= ones;
              // output the original digits
    System.out.print("" + thousands + hundreds + tens +
    + ones + "");
              // do the encryption
              // add 7 to each digit
              thousands += 7;
              hundreds += 7;
              tens += 7;
              ones += 7;
              // mod each digit by ten
              thousands %=10;
              hundreds %=10;
              tens %=10;
              ones %=10;
              // swap the 1st (thousands) and 3rd (tens) digits
              int temp = thousands;
              thousands = tens;
              tens = temp;
              // swap the 2nd and the 4th digit
              int temp1 = hundreds;
              hundreds = ones;
              ones = temp1;
              // output the encrypted integer
              System.out.printf("%d", number);
    Next, I am to write a seperate application that
    inputs an encrypted four digit number and decrypts it
    to form the original number. I am a little confused
    how to go about this. Thanks in advance!!!
    Right, and you made two rookie mistakes:
    (1) You put all that code into the main method, where nothing else can get at it.
    (2) You just print the number to System.out.
    Move all that code into a method called encrypt that takes an input number and returns the output encrypted value. Now any other class can just call that method and let your first class do all the work.
    Write a second method in that same class that reverses the encryption - call it decrypt. It'll take encrypted input and return the decrypted output.
    %

Maybe you are looking for

  • User Accounts and ORA-01722: invalid number error

    Hello, I have been using Express for a month or so now but have very limited knowledge of how it works. My Problem: I have a listing screen for user records which creates records in table QAS_USERS. When I add a record it saves the data OK and put th

  • Is there any customer support for this product?

    I have a client who has sent me two documents. When I log on using my Adobe ID it says the Document could not be found because of one of the following reasons: * Document was rejected by one of signatories * Document was cancelled by initiator * Docu

  • I have installed flash on my laptop, ie, but computer says no flash is installed. Help!

    I have Windows Vista SP2, 4gb, 32 bit.    Each time I install Flash 11 (via links) or 11.5 (directly), the screen tells me either I must close IE (task manager says it is closed) or install is complete.  But when I go to the adobe flash site, it says

  • Free apps on iOS 7 update not available

    When I updated my iPhone and iPad to iOS 7 I didn't get the free pages, numbers, iMovie etc apps, any ideas on retrieving them?

  • OS X 10.8.2 Software update issue

    I'm having the following problem with my mid-2011 MacBook Air.  I believe it started subsequent to upgrading to iTunes 11.0.  Here's what happens when selecting "Software Update" from the Apple Menu. Software "Updates" tab: "We could not complete you