Simple Class

I am looking for help in developing a simple program to track input and then convert the running total when prompted. I am a novice, I know I need to implement a simple class, then use an object to track data in the class. I have the input parameters setup with the if-else supporting it.
Looking for an example of reading point that would assist. Like I said, this is a simple program, not in production, more training level
Thanks

Well basically I need to take the user input value
and store it somewhere, continue to prompt for more
input for an undetermined period, then when prompted,
print out the running total.So, you don't know how to do any of that?
Start here:
Sun's basic Java tutorial
Sun's New To Java Center. 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. A couple dozen code examples that supplement The Java Developers Almanac.
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 (Available online.)
Joshua Bloch's Effective Java
Bert Bates and Kathy Sierra's Head First Java.
James Gosling's The Java Programming Language. Gosling is
the creator of Java. It doesn't get much more authoratative than this.

Similar Messages

  • Difference between narrow() method usage and simple class cast for EJB

    Hi,
    I have a very simple question:
    what is the difference between PortableRemoteObject.narrow(fromObj,
    toClass) method usage and simple class cast for EJB.
    For example,
    1)
    EJBObject ejbObj;
    // somewhere in the code the home.create() called for bean ...
    ABean a = (ABean)PortableRemoteObject.narrow(ejbObj,ABean.class);
    OR
    2)
    EJBObject bean;
    // somewhere in the code the home.create() called for bean ...
    ABean a = (ABean)ejbObj;
    Which one is better?
    P.S. I'm working with WL 6.1 sp2
    Any help would be appreciated.
    Thanks in advance,
    Orly

    [email protected] (Orly) writes:
    Hi,
    I have a very simple question:
    what is the difference between PortableRemoteObject.narrow(fromObj,
    toClass) method usage and simple class cast for EJB.
    For example,
    1)
    EJBObject ejbObj;
    // somewhere in the code the home.create() called for bean ...
    ABean a = (ABean)PortableRemoteObject.narrow(ejbObj,ABean.class);
    OR
    2)
    EJBObject bean;
    // somewhere in the code the home.create() called for bean ...
    ABean a = (ABean)ejbObj;
    Which one is better?(1) is mandated by the spec. It is required because CORBA systems may
    not have sufficient type information available to do a simple case.
    P.S. I'm working with WL 6.1 sp2 You should always use PRO.narrow()
    andy

  • Having trouble using a simple class..New to AS3

    Hello Everyone,
    I am new to AS3 but not to AS2. I have written a simple class
    and when I import it, I don't see the object that should be created
    upon calling the constructor. Can you guys tell me where am I going
    wrong. And I am very puzzled about 'document class'. Yes, I have
    google numerous threads on "document class" but still very shaky on
    this matter. Here is my simple class which should place a button
    object on the stage when I create a new object of this class.
    Once I have created the BTN class, I have made sure that I
    have button component in my library, I then instantiate the object
    by creating a new CS3 file and importing my class:
    import com.learning.as3.*;
    var b:BTN = new BTN();
    When I test the movie, I get the following errors:
    1172: Definition com.learning.as3 could not be found.
    1046: Type was not found or was not a compile-time constant:
    BTN.
    1180: Call to a possibly undefined method BTN.
    Any help would highly be appreciated.
    Thanks you.

    Hello Ned,
    Yes, I have made sure that my directory structure exist as it
    should be and yet I still get the errors.
    Thanks a lot.

  • Help on dynamically loading of simple classes - ClassLoader

    Hello,
    does somebody know how to load simple classes with java.lang.ClassLoader in a stateless session bean running on SneakPreview 6.40?
    i found many solutions for j2ee servers on the net but no one works. i always get a ClassNotFoundException but i can read the class file to a byte array.
    this is one way i tried to solve the problem:
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    Class aClass = Class.forName(strClassName, true, loader);
    hopefully someone can help me,
    thanks
    erich

    Hi Erich,
    for such a kind of problems (not knowing for sure where the classloader is looking for the class) I am used to use http://www.sysinternals.com/ntw2k/source/filemon.shtml
    Just write <i>Class.forName("ABC123", true, loader);</i> and then you can check the places where the classloader is looking for this ABC123 class...
    Hope it helps
    Detlev

  • What is wrong with my simple class program?

    Ok, I'm writing a simple class called 'Frog', which will keep track of the position enter by a user. The program will ask for the initial position for the frog. It will then ask for how many steps it want the frog to jump. Then it will output the new position of it. But for some reason, it doesn't work. It always output 0 for some reason.
    import java.io.*;
    import java.util.*;
    - frog program class.
    frog will start on a position.
    user will be prompt to ask how many jump to forward.
    public class beta
         public static void main(String args[]) throws IOException
              class Frog
              int newPos;
                   int Position () //return postion of the frog
                   return newPos;
                   void PositionStart (int newPos) //initial postion of the frog
                   newPos = newPos;
                   int Jump(int stepsForward, int newPos)
                        newPos+=stepsForward;
                        return newPos;
                   int PrevPos(int newPos)
                   return newPos-1;
                   int NextPos(int newPos)
                   return newPos+1;
                   boolean isMagicSquare(int newPos)
                        if(newPos == 5) return true;
                        else return false;
         BufferedReader key = new BufferedReader(new InputStreamReader(System.in));
         Frog joe = new Frog();
         int pos = 0, stepsFoward = 0;
                   //input 1-9
                   do
                        System.out.println("Enter a position for the frog: ");
                        pos = Integer.parseInt(key.readLine()); //reads in an integer
                   }while(pos < 1 || pos > 9);
                   joe.PositionStart(pos); //initialize the position for the frog
                   System.out.println("Pos: " + joe.Position()); //position
                   System.out.println("How many steps to jump: ");
                   stepsFoward = Integer.parseInt(key.readLine());
                   joe.Jump(stepsFoward,joe.Position());
                   System.out.println("New Position: " + joe.Position());               
    }

    You have method argument parameters with the same name as a member variable; as in:
    void PositionStart (int newPos) {
            newPos = newPos;
    }You need to identify to the compiler which variable is which, class member variables in cases like this should be qualified with the this keyword; as in:
    void PositionStart (int newPos) {
            this.newPos = newPos;
    }Dave

  • Simple class runs 3x slower inside 8i than outside...why?

    I have a simple class to read a large number of numbers (1E6) and sort them using the java Collections.sort(). I tested the class in the JVM run as a Procedure and externally as a simple class on my desktop.Running Oracle 8i on Linux Redhat7.2. The external version runs about 3 times faster and I have no idea why.
    Running the class in the JVM: Server is a Compaq P800-256128US with PIII 800 MHz 256 KB cache & 256MB PC-133 and SCSI drives.
    Connection time: 0.004 seconds
    ArrayList build: 223.27 seconds
    Collection.sort(): 101.29 seconds
    Running the class on my workstation: Machine is a Compaq DeskPro w/PIII with 256MB.
    OP:Connecting...
    ----The operation took 5.734 seconds
    OP:Building List...
    ----The operation took 81.141 seconds
    OP: Sorting 1000000 items...
    ----The operation took 6.859 seconds
    Here is the class trivial logic:
    Connection conn = DriverManager.getConnection("jdbc:default:connection:");
    List list = new ArrayList();
    stmt = conn.createStatement();
    ResultSet rset = stmt.executeQuery("select List from NUMBERS");
    while (rset.next())
    list.add(Integer.valueOf(rset.getString(1)));
    Collections.sort(list);//sorting
    I have timing calls embedded not shown here in both versions to measure and of course the connection is different for external call.
    What do you think of these results? What should I check?
    Thanks,
    Chris

    Id like to follow up with some questions:
    1.)     Oracle documentation states that PL/SQL is the preferred tool for data intensive jobs. And Java Stored Procedures are preferred for more algorithmic jobs. This seems contrary to what you state. Can you clearify?
    2.)     When you say gen. purpose and cpu bound Java code, do you mean algorithmic code?
    3.)     I assume the points 1 and 2 in your response suggest that it takes so long to get the Java environment up and running that it is killing the performance of my simple algorithm...is that what you mean?
    4.)     My real goal is to use intelligent agents (use AI algorithms that are very expensive computationally) and are invoked upon updates and continually train on newly inserted data. The fact these guys can live in the Oracle JVM, be invoked upon an update using a trigger and call an EJB client in warning of a particular condition is what made me fall in love with this solution that Oracle provides. But do you think I am asking too much or Im going a bit beyond what the JVM is for?

  • A simple class vs. Stateless Session Bean

    If I want a stateless bean to do some simple work such as give it a number A
              and get A+10 in return, does the Stateless session bean really perform
              better than a simple class? In my project, there are lots of simple job like
              this, which one should I use? A Stateless session bean or a simple class?
              Besides, when is the right time to use a stateful session bean? I use the
              servlet to keep user information in the session, and than have the stateless
              session bean working with it...This pattern meets most requirement....So I'm
              wondering in what situation should I need to use stateful session bean?
              Thanks!
              

    - It is far better to use a stateless session bean when implementing the session-facade pattern.
    - Keeping a home interface on the object won't make him stateful.
    - with the stateless beans, you do not decide when they're created. The container does.
    - The number of entity beans is not so important. The only thing important is to have a remote methode in your stateless(es) for each atomic transaction ("atomic" meaning here "you cannot cut").
    /Stephane

  • A Simple Class

    Ok..ive tried an example of creating a simple class...but im getting an error when i try to load the jsp page within the web browser.
    org.apache.jasper.JasperException: Attempted a bean operation on a null object.
    My java code
    package booklibrary;
    public class Book
         private String title;
         public String getTitle(){
              return title;
         public void setTitle(String newTitle){
              this.title = newTitle;
    My JSP code
    <HTML>
    <HEAD>
    <TITLE>A Simple Class</TITLE>
    </HEAD>
    <BODY>
    <JSP:useBean id = "myBook" class = "booklibrary.Book"/>
    <JSP:setProperty name = "myBook"
                                  property = "title"
                                  value = "Begining JSP 2.0"/>
    Book Title: <jsp:getProperty name = "myBook" property = "title" />
    </BODY>
    </HTML>
    Anyone able to help me.Please

    import javax.swing.JOptionPane;
    public class SimpleDialog {
    public static void main(String[] args) {
      String inp = JOptionPane.showInputDialog(null,"input string");
      JOptionPane.showMessageDialog(null, "hi -- " + inp);
      //JOptionPane frame = new JOptionPane();
      //JOptionPane.showMessageDialog(frame, "hi");
      System.exit(0);
    } // method
    } // class hiDialog

  • How to deploy a simple class in Tomcat 5

    Hi All,
    Need your help...
    I have just started learning Java and JSP.
    I was trying to write a simple Shopping Cart program in JSP. I have created a directory under my root context directory. But while I am invoking the JSP, I am getting a error like this:
    org.apache.jasper.JasperException: Unable to compile class for JSP
    An error occurred at line: 18 in the jsp file: /JspSessionCart/build/carts.jsp
    Generated servlet error:
        [javac] Compiling 1 source file
    C:\Program Files\Apache Software Foundation\Tomcat 5.0\work\Catalina\localhost\mycontext\org\apache\jsp\JspSessionCart\build\carts_jsp.java:64: package sessions does not exist
          sessions.DummyCart cart = null;
                  ^
    An error occurred at line: 18 in the jsp file: /JspSessionCart/build/carts.jsp
    Generated servlet error:
    C:\Program Files\Apache Software Foundation\Tomcat 5.0\work\Catalina\localhost\mycontext\org\apache\jsp\JspSessionCart\build\carts_jsp.java:66: package sessions does not exist
            cart = (sessions.DummyCart) _jspx_page_context.getAttribute("cart", PageContext.SESSION_SCOPE);
                            ^
    An error occurred at line: 18 in the jsp file: /JspSessionCart/build/carts.jsp
    Generated servlet error:
    C:\Program Files\Apache Software Foundation\Tomcat 5.0\work\Catalina\localhost\mycontext\org\apache\jsp\JspSessionCart\build\carts_jsp.java:68: package sessions does not exist
              cart = new sessions.DummyCart();
                                 ^
    An error occurred at line: 33 in the jsp file: /JspSessionCart/build/carts.jsp
    Generated servlet error:
    C:\Program Files\Apache Software Foundation\Tomcat 5.0\work\Catalina\localhost\mycontext\org\apache\jsp\JspSessionCart\build\carts_jsp.java:92: package util does not exist
    out.print(util.HTMLFilter.filter(items));
    ^
    An error occurred at line: 33 in the jsp file: /JspSessionCart/build/carts.jsp
    Generated servlet error:
    Note: C:\Program Files\Apache Software Foundation\Tomcat 5.0\work\Catalina\localhost\mycontext\org\apache\jsp\JspSessionCart\build\carts_jsp.java uses unchecked or unsafe operations.
    An error occurred at line: 33 in the jsp file: /JspSessionCart/build/carts.jsp
    Generated servlet error:
    Note: Recompile with -Xlint:unchecked for details.
    4 errors
         org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:127)
         org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:351)
         org.apache.jasper.compiler.Compiler.generateClass(Compiler.java:415)
         org.apache.jasper.compiler.Compiler.compile(Compiler.java:458)
         org.apache.jasper.compiler.Compiler.compile(Compiler.java:439)
         org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:553)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:291)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:301)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:248)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
    I am not able to understand what to do? Do I need to set any CLASSPATH? If yes, kindly tell me what would the path for CLASSPATH.
    Kindly help me....
    Thanks.,
    Ujjal                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    Ujjal wrote:
    Hi All,
    Need your help...
    I have just started learning Java and JSP.
    I was trying to write a simple Shopping Cart program in JSP. I have created a directory under my root context directory. But while I am invoking the JSP, I am getting a error like this:
    org.apache.jasper.JasperException: Unable to compile class for JSP
    An error occurred at line: 18 in the jsp file: /JspSessionCart/build/carts.jspMaybe you should look at that JSP. It's incorrect, obviously.
    Look, here's a hint:
    C:\Program Files\Apache Software Foundation\Tomcat 5.0\work\Catalina\localhost\mycontext\org\apache\jsp\JspSessionCart\build\carts_jsp.java:66: package sessions does not exist
    cart = (sessions.DummyCart) jspxpage_context.getAttribute("cart", PageContext.SESSION_SCOPE);Why isn't this a good enough guide?

  • Need simple class for communicating with Solaris account

    Hey, gang. After over a week of searching this forum and the Web for a solution, I'm stuck. I hope someone here can help.
    I've got a Java application intended to run on both Windows and Solaris systems that needs to perform the following automated operations:
    1. Connect to a user account on a Solaris server.
    2. Login.
    3. Run an sccs command.
    4. Retrieve the output from the sccs command.
    I can run commands (such as sccs) directly from Java; I've worked out how to do that. My situation is that I need to run sccs from an authorized account so that all file checkin/checkout operations are tagged properly. So the requirement to connect to a server isn't one I can ignore. I also don't need a full-up interactive client interface -- this needs to be an automated process.
    What I'm hoping is that someone here will be willing to provide (or point me to) some relatively simple source code I can call to do this stuff. Maybe an example of a class that uses Socket and a couple of streams to programmatically connect to a server, send commands, and capture input. That's really all I need.
    I've tried calling the Jakarta Commons telnet class to connect to the Solaris server, but it's more overhead than I need. (Plus the input stream kept blocking when I tried to use it in a purely automated mode.) I've also tried rolling my own code using the minimal info available on Google, but have not been able to figure out the magic words necessary to get anything back but gibberish. (InputStream and BufferedReader just do not seem to want to cooperate. Either I get back only garbage text, or readLine() or read() gets nothing and just sits and waits until the timeout.)
    So I turn to the experts here. If anyone can offer (or direct me to) any simple, non-libraried source code that enables my Java code to connect to and talk to a Solaris machine, I'd be grateful.
    Thanks!

    I was hoping a separate server-side process wouldn't be needed -- if you're thinking of something like RMI, that's also a bit heavyweight for my needs. I know I can talk to the remote server on telnet port 23, though.
    Further experimentation today with the Jakarta net library has generated something that works using their telnet classes. (After I asked for help here, of course. The same thing happens when I shop for groceries....) But using this leaves me referencing an external library that:
    1. has functionality I don't need that complicates the code, and
    2. forces me to address licensing requirements.
    So I'd still love to see an example of a telnet-like Java class that strips away all the non-essentials in the Jakarta telnet library code, leaving behind a simple public domain class that can be used to connect to a remote host and transfer characters over that connection.
    I appreciate that this may be asking for a lot, but as they say, if you don't ask, you don't get. ;-)
    Thanks!

  • Is it possible to execute simple class

    Sir,
    Is it possible to execute a simple program written in java in
    jdeveloper. If yes please let me know how to that.
    I creted a class using class wizard and added the following
    statement;
    System.out.println("testing");
    I able to compile the program without error, but how to execute
    it.
    raghu
    null

    Hi Jun Wu,
    Because without deploying, it doesn't allow me check how my java webdynpro application works!!
    I  need to execute my java web dynpro application and I dont have any access to SDM pins/passwords.
    Please share your valuable thoughts on the same.
    regards,
    Ajeeth Kumar S

  • Simple class Evolution with DPL fails.

    Hi
    I added a simple integer field to an existing class, used with DPL and during startup next time get this error. From the documentation, this type of class evolution should work automatically. But I get following exception. Does it require some extra configuration? I cant seem to locate that in the documentation.
    com.sleepycat.persist.evolve.IncompatibleClassException: Changes to the fields or superclass were detected when evolving class: com.pkg.TestClass version: 0 to class: com.ul.users.UserProfile version: 0 Error: A new higher version number must be assigned
    at com.sleepycat.persist.impl.PersistCatalog.<init>(PersistCatalog.java:338)
    at com.sleepycat.persist.impl.Store.<init>(Store.java:172)
    at com.sleepycat.persist.EntityStore.<init>(EntityStore.java:148)

    Hi,
    The exception message "A new higher version number must be assigned" means that you have to explicitly specify a version parameter in your Entity or Persistent annotation.
    This is explained in the com.sleepycat.persist.evolve package description here:
    http://www.oracle.com/technology/documentation/berkeley-db/je/java/com/sleepycat/persist/evolve/package-summary.html
    --mark                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Please help with simple Classes understanding

    Working further to understand Class formation, and basics.
    At the Java Threads Tutorial site:
    http://java.sun.com/docs/books/tutorial/essential/threads/timer.html
    Goal:
    1)To take the following code, and make it into 2 seperate files.
    Reminder.java
    RemindTask.java
    2)Error Free
    Here is the original, functioning code:
    import java.util.Timer;
    import java.util.TimerTask;
    * Simple demo that uses java.util.Timer to schedule a task
    * to execute once 5 seconds have passed.
    * http://java.sun.com/docs/books/tutorial/essential/threads/timer.html
    public class Reminder {
        Timer timer;
        public Reminder(int seconds) {
            timer = new Timer();
            timer.schedule(new RemindTask(), seconds*1000);
        class RemindTask extends TimerTask {
            public void run() {
                System.out.println("Time's up!");
                timer.cancel(); //Terminate the timer thread
        public static void main(String args[]) {
            new Reminder(5);
            System.out.println("Task scheduled.");
    }Here is what I tried to 2 so far, seperate into 2 seperate files:
    Reminder.java
    package threadspack;    //added this
    import java.util.Timer;
    import java.util.TimerTask;
    * Simple demo that uses java.util.Timer to schedule a task
    * to execute once 5 seconds have passed.
    * http://java.sun.com/docs/books/tutorial/essential/threads/timer.html
    public class Reminder {
        Timer timer;
        public Reminder(int seconds) {
            timer = new Timer();
            timer.schedule(new RemindTask(), seconds*1000);
        public static void main(String args[]) {
            new Reminder(5);
            System.out.println("Task scheduled.");
    }and into
    RemindTask.java
    package threadspack;  //added this
    import java.util.Timer;
    import java.util.TimerTask;
    import threadspack.Reminder; //added this
    * http://java.sun.com/docs/books/tutorial/essential/threads/timer.html
    public class RemindTask extends TimerTask
    Timer timer; /**here, I added this, because got a
    "cannot resolve symbol" error if try to compile w/out it
    but I thought using packages would have negated the need to do this....?*/
         public void run() {
                System.out.println("Time's up!");
                timer.cancel(); //Terminate the timer thread
    }After executing Reminder, the program does perform, even does the timing, however, a NullPointerException error is thrown in the RemindTask class because of this line:
    timer.cancel(); //Terminate the timer thread
    I am not sure of:
    If I have packages/import statements setup correctly
    If I have the "Timer" variable setup incorrectly/wrong spot.
    ...how to fix the problem(s)
    Thank you!

    Hi there!
    I understand that somehow the original "Timer" must
    be referenced.
    This is a major point of confusion for me....I
    thought that when importing
    Classes from the same package/other packages, you
    would have directly
    access to the variables within the imported Classes.I think you have one of the basic points of confussion. You are mixing up the concept of a "Class" with the concept of an "Object".
    Now, first of all, you do not need packages at all for what you are trying to do, so my advice is you completely forget about packages for the moment, they will only mess you up more. Simply place both .class files (compiled .java files) in the same directory. Your program is executing fine, so that indicates that the directory in which you have your main class file is being included in your classpath, so the JVM will find any class file you place there.
    As for Classes/Objects, think of the Class as the map in which the structure of a building is designed, and think of the Object as the building itself. Using the same technical map the architect defines, you could build as many buildings as you wanted. They could each have different colors, different types of doors, different window decorations, etc... but they would all have the same basic structure: the one defined in the technical map. So, the technical map is the Class, and each of the buildings is an object. In Java terminology, you would say that each of the buildings is an "Instance" of the Class.
    Lets take a simpler example with a class representing icecreams. Imagine you code the following class:
    public class Icecream{
         String flavor;
         boolean hasChocoChips;
    }Ok, with this code, what you're doing is defining the "structure" of an icecream. You can see that we have two variables in our class: a String variable with the description of the icecream's flavor, and a boolean variable indicating whether or not the icecream has chocolate chips. However, with that code you are not actually CREATING those variables (that is, allocating memory space for that data). All you are doing is saying that EACH icecream which is created will have those two variables. As I mentioned before, in Java terminology, creating an icecream would be instantiating an Icrecream object from the Icecream class.
    Ok, so lets make icrecream!!!
    Ummm... Why would we want to make several icecreams? Well, lets assume we have an icecream store:
    public class IcecreamStore{
    }Now, we want to sell icecreams, so lets put icecreams in our icecream store:
    public class IcecreamStore{
         Icecream strawberryIcecream = new Icecream(); //This is an object, it's an instance of Class Icecream
         Icecream lemonIcecream = new Icecream(); //This is another object, it's an instance of Class Icecream
    }By creating the two Icecream objects you have actually created (allocated memory space) the String and boolean variable for EACH of those icecreams. So you have actually created two String variables and two boolean variables.
    And how do we reference variables, objects, etc...?
    Well, we're selling icecreams, so lets create an icecream salesman:
    public class IcecreamSalesMan{
    }Our icecream salesman wants to sell icecreams, so lets give him a store. Lets say that each icecream store can only hold 3 icecreams. We could then define the IcecreamStore class as follows:
    public class IcecreamStore{
         Icecream icecream1;
         Icecream icecream2;
         Icecream icecream3;
    }Now lets modify our IcecreamSalesMan class to give the guy an icecream store:
    public class IcecreamSalesMan{
         IcecreamStore store = new IcecreamStore();
    }Ok, so now we have within our IcecreamSalesMan class a variable, called "store" which is itself an object (an instance) of the calss IcecreamStore.
    Now, as defined above, our IcecreamStore class will have three Icecream objects. Indirectly, our icecream salesman has now three icecreams, since he has an IcecreamStore object which in turn holds three Icecream objects.
    On the other hand, our good old salesman wants the three icecreams in his store to be chocolate, strawberry, and orange flavored. And he wants the two first icecreams to have chocolate chips, but not the third one. Well, here's the whole thing in java language:
    public class Icecream{ //define the Icecream class
         String flavor;
         boolean hasChocoChips;
    public class IcecreamStore{ //define the IcecreamStore class
         //Each icecream store will have three icecreams
         Icecream icecream1 = new Icecream(); //Create an Icecream object
         Icecream icecream2 = new Icecream(); //Create another Icecream object
         Icecream icecream3 = new Icecream(); //Create another Icecream object
    public class IcecreamSalesMan{ //this is our main (executable) class
         IcecreamStore store; //Our class has a variable which is an IcecreamStore object
         public void main(String args[]){
              store = new IcecreamStore(); //Create the store object (which itself will have 3 Icecream objects)
              /*Put the flavors and chocolate chips:*/
              store.icecream1.flavor = "Chocolate"; //Variable "flavor" of variable "icecream1" of variable "store"
              store.icecream2.flavor = "Strawberry"; //Variable "flavor" of variable "icecream2" of variable "store"
              store.icecream3.flavor = "Orange";
              store.icecream1.hasChocoChips = true;
              store.icecream2.hasChocoChips = true;
              store.icecream3.hasChocoChips = false;
    }And, retaking your original question, each of these three classes (Icecream, IcecreamStore, and IcecreamSalesMan) could be in a different .java file, and the program would work just fine. No need for packages!
    I'm sorry if you already knew all this and I just gave you a stupid lecture, but from your post I got the impression that you didn't have these concepts very clear. Otherwise, if you got the point, I'll let your extrapolate it to your own code. Should be a pice of cake!

  • Help on simple class definition

    This is just the class definition (main() is in its own file, but I was wondering if someone could help me figure out what is wrong w/ the code. I am trying to make a simple program that asks, "what is your name?", than you enter your name, and it says "hello, john, today is feb, 3rd" (or whatever).
    I'm not even sure if the code is right to do what I want to do, but I can't really figure that out if it won't compile.
    Oh, and here is the error message I am getting.
    HelloWorld.java:26: ')' expected
    System.out.println ("Hello " + yourName
    ^
    1 error
    import java.util.*;
    import java.io.*;
    class HelloWorld extends Object
    HelloWorld()
    BufferedReader in = new BufferedReader (new
    InputStreamReader(System.in));
    Date currentDate = new Date();
    String yourname;
    System.out.println ("Hello, please enter your name: ");
    yourName = in.readLine();
    System.out.println ("Hello " + yourName
    "Today is, " + currentDate );

    At this point in your code a java.io.IOException might occur.
    You have to declare your exception to be thrown:
    HelloWorld() throws IOException Or you catch the occuring exception in a try-catch-block:
    HelloWorld()
      try
       //your code here
      catch (IOException e)
       //What should be done with the exception
    Guinevere                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Simple Class and the Display List

    I have very simple code for a class:
    package
        import flash.text.TextField;
        import flash.display.Sprite;
        public class Greeter extends Sprite
            public function Greeter()
                var txtHello:TextField = new TextField();
                txtHello.text = "Hello World";
                trace("hi");
                addChild(txtHello);
    The above file is saved as Greeter.as in say folder  C:\test
    I then create a Fla file named test_display.fla (saved in C:\test) and its contents are:
    import Greeter;
    var tt:Greeter = new Greeter();
    Now the Output window shows hi due to the trace statement but the addChild method should show
    Hello World in the Flash movie but it does not. The only way to get Hello World to the Flash Movie
    is to change the test_display.fla to:
    import Greeter;
    var tt:Greeter = new Greeter();
    addChild(tt);
    In other words I have to use the addChild method twice ( once in Greeter.as and once in test_display.fla )
    to get Hello World to display in the Flash movie. Does anyone know why this is so?

    Thanks Andrei1,
    I honestly am having trouble with your answer. I am sure it is correct, I just don't get it right now.
    As a slight twist on the original code say for example you want to get Hello World to output
    inside the output window NOT the Flash movie. I see the code snippet  inside the class it reads:
    var txtHello:TextField = new TextField();
    txtHello.text = "Hello World";
    So now inside the FLA file ( not inside the class file )  I have tried various ways to get Hello World to print in output window:
    I have tried trace(tt.text);  and I get an error.
    So the question is I know tt is an instance of Greeter and inside Greeter I see
    where Hello World is assigned via:
    txtHello.text = "Hello World";
    So the question is why can't I get Hello World to print in the output window ( using trace) via
    the instance tt somehow?

Maybe you are looking for