Instantiation outside main method

Why can't you do the following? I get an error message: Java programs\Exp.java:14: non-static variable scan cannot be referenced from a static context
boxes = scan.nextInt(); I don't understand this message since you can instantiate objects and initialize variables within a class and outside a method with no problem. What's so special about the main method that you cannot do this? By the way, I know how to fix this. I just want to know why you can't do this.
import java.util.Scanner;
public class Exp
     Scanner scan = new Scanner(System.in);
     public static void main(String[] args)
          int boxes;
          System.out.println("Enter a number: ");         
          boxes = scan.nextInt();
          if(boxes > 5)
               System.out.println("So what!");
          else
               System.out.println("Less than!");
               System.out.println("I don't know.");
}

afried01 wrote:
Well, if the objects are instantiated outside the main method then none of them could be used inside that method. You would have to use them outside the main method or any other static method, that is, if I'm getting your point correctly.No. You could still use them within the main method, but first you'd have to instantiate an object of the class.
Keep in mind that your main method should be pretty lightweight. You should only use it to bootstrap your program (i.e., to start it up at the beginning). So generally you'd instantiate the primary classes of your application, maybe call an initialization or start method on one of them, etc. If your main method is more than 15 or so lines of code it's probably too heavy.
Or you could just make the field (outside the main class) static, so the (static) main method could use them, but as mentioned already that's generally not the right approach.

Similar Messages

  • Methods outside main()

    Hello,
    Can have methods outside main() ?
    I am trying to call abc and says non-static method abc() cannot be referenced from a static context
    abc();
    When I make it static it is compiling but I dont want it to be a static method...
    public static void main( String[] as )
              abc();
         public void abc( )
    //Prints Hello
    }

    No I dont have too much of a C/C++ background but I am
    curious about static variable and methods..
    I can understand that we need to use static methods
    when you want the value to be same across all objects
    and at the same time can be changed....
    for example:
    Object 1
    public static String loc = "location:4444";
    Object2 calls
    loc = "location:5555"
    so if object 2 changes port or location... Object 1's
    loc also changes...
    So this means that when we are going to change the loc
    later on somewhere we can make it static... Otherwise
    if our location will never change and always be
    location:4444 then we are better off making that
    variable final and not static.
    Am I right?I'm not really following what you're asking, but static and final are not mutually exclusive. One of the most common uses of static member variables is as class-wide constants--either public or private--in which case they are also final.

  • Object life in main method after frame created

    hi
    i'm having a slight problem with the life of an object i'm creating in the main method of my application.
    i have a JDesktopPane that is initialised in the main class's main method and constructor. within the main method i also add the first internal frame to the desktop.
    after the user completes the details of the first frame, another is called (from this first frame) and the first frame is disposed.
    the problem is that although all subsequent internal frames added to the desktop outside the main class, they are garbage collected with no problems (i'm using a profiler), however the first frame and the frame created from that first frame are never collected due to the reference maintained in the main class. i've tried adding the creation of these frames outside the main class but given that these methods are called from main the reference is still maintained.
    is there any way to create those first 2 frames without the reference being maintained in the main class such that they become elegible for garbage collection? do i have it all wrong perhaps and my approach is bad?? any help would be greatly appreciated.
    thanks heaps.
    Takis

    hi
    thanks for your reply.
    i tried that and it didn't work. the instance of that first internal frame is still there.
    i really am at a loss with this one.
    any other suggestions would be greatly appreciated.
    Takis

  • Need help - how to run this particular method in the main method?

    Hi all,
    I have a problem with methods that involves objects such as:
    public static Animal get(String choice) { ... } How do we return the "Animal" type object? I understand codes that return an int or a String but when it comes to objects, I'm totally lost.
    For example this code:
    import java.util.Scanner;
    interface Animal {
        void soundOff();
    class Elephant implements Animal {
        public void soundOff() {
            System.out.println("Trumpet");
    class Lion implements Animal {
        public void soundOff() {
            System.out.println("Roar");
    class TestAnimal {
        public static void main(String[] args) {
            TestAnimal ta = new TestAnimal();
            ta.get(); // error
            // doing Animal a = new Animal() is horrible... :(                   
        public static Animal get(String choice) {
            Scanner myScanner = new Scanner(System.in);
            choice = myScanner.nextLine();
            if (choice.equalsIgnoreCase("meat eater")) {
                return new Lion();
            } else {
                return new Elephant();
    }Out of desperation, I tried "Animal a = new Animal() ", and it was disastrous because an interface cannot be instantiated. :-S And I have no idea what else to put in my main method to get the code running. Need some help please.
    Thank you.

    Hi paulcw,
    Thank you. I've modified my code but it still doesn't print "roar" or "trumpet". When it returns a Lion or an Elephant, wouldn't the soundOff() method get printed too?
    refactored:
    import java.util.Scanner;
    interface Animal {
        void soundOff();
    class Elephant implements Animal {
        public void soundOff() {
            System.out.println("Trumpet");
    class Lion implements Animal {
        public void soundOff() {
            System.out.println("Roar");
    class TestAnimal {
        public static void main(String[] args) {
            Animal a = get();
        public static Animal get() {
            Scanner myScanner = new Scanner(System.in);
            System.out.println("Meat eater or not?");
            String choice = myScanner.nextLine();
            if (choice.equalsIgnoreCase("meat eater")) {
                return new Lion();
            } else {
                return new Elephant();
    }The soundOff() method should override the soundOff(); method in the interface, right? So I'm thinking, it should print either "roar" or "trumpet" but it doesn't. hmm..

  • Main method errors

    I am trying to create the Euclid Algorithm in a simple command line application. I get the following error when I try to compile...
    Cannot make a static reference to the non-static method getInputs()
    Cannot make a static reference to the non-static method doGCD()
    Cannot make a static reference to the non-static method doLCM()
    public class Euclid
         public static void main(String[] args)
    //This is where I try to invoke the methods getInputs(), doGCD(), and doLCM() but it errors.
         public void getInputs()
         {      //User defined inputs
         public void doGCD()     
         {      //Algorithm
         public void doLCM()     
         {      //Algorithm               
    Is there a proper way to invoke these because I've been researching and I think I need to create objects, but I'm not sure what that means.

    adam.lee wrote:
    Try putting your methods outside of the main method. What does that even mean? They are outside the main() method. Unless you mean call them somewhere else, but that doesn't make sense because if you can't call any methods inside the main() method then you can't make your program do anything.
    You can call them inside the main method but you might have to put 'static' in front.Terrible advice. You only ever make a method static if it needs to be static. Never, ever, ever, ever, EVER make a method static just for the sake of getting your program to compile. This breeds ignorance of what the term 'static' even means. Only make it static if it should belong to the class, and not an object of the class. A method like getInputs() shouldn't be static because each Euclid object could potentially have it's own inputs.

  • Beginner - class & main method question

    Hello, I am still really new to OOP and Java. I came across an example in the book I am using that threw me for a loop.
    ex.
    class MyClass {
    public static void main(String [] args) {
    int x = 42;
    MyClass y = new MyClass();
    int z = y.go(x);
    int go(int arg) {
    arg = arg * 2;
    return arg;
    what I am confused about is the creation of a new class that contains the main method (MyClass y = new MyClass()), wouldn't this create a new class that also has a main method? Or is this the kind of code I will never encounter outside an example in a book and shouldn't worry about it :-)
    Thanks

    Since the main method is static, it would be invoked through MyClass.main(...). Note that this is not actually creating an object, just calling a static method.
    Creating an object is an entirely different story. MyClass mc = new MyClass(); instantiates a new object of the class MyClass. You couldn't do mc.main(...) because main is static. You can call things such as mc's go() method because they are not static and thus belong to objects of that class, rather than the class itself.
    ...Or something. That all made sense in my head, but if it didn't make sense to you just tell me.

  • Multiple main methods

    Can we have more than one main method in a class/in various classes?if not why? and if yes then is that possible to call main() method with some other object nam,,,,say for eg...j.main()?
    As I'm new to java if anybody can explain me using an example as applicable it would be a better understanding for me over the concept

    It's not necessary to have main in a class and it's also ok to have main in multiple classes.
    You can also have multiple methods named 'main' in a class ( confusing, but legal ) as long as they follow the rules for overloading.
    The entry point for a Java program has to be a method with the signature
    public static void main ( String [] args )If you don't have this, you can't run that class. If you do, you can.
    The method has to be public because it will be called by the OS. It also has to be static since the object will not be instantiated till later; the runtime environment needs to be able to call the method without having to instantiate an object. The String array as parameter is to allow passing of command line arguments to the class.
    EDIT: A little slow there.
    Edited by: nogoodatcoding on Oct 16, 2007 5:48 PM

  • Com.sun.tools.javac.Main: method compile errors

    I had a working web project the other day, and something happened that caused every page to start throwing this error:
    # javax.servlet.ServletException: com.sun.tools.javac.Main: method compile([Ljava/lang/String;Ljava/io/PrintWriter;)I not found
    # at com.ibm.ws.webcontainer.jsp.servlet.JspServlet.service(JspServlet.java:779)
    # at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
    # at com.ibm.ws.webcontainer.servlet.StrictServletInstance.doService(StrictServletInstance.java:110)
    # at com.ibm.ws.webcontainer.servlet.StrictLifecycleServlet._service(StrictLifecycleServlet.java:174)
    # at com.ibm.ws.webcontainer.servlet.IdleServletState.service(StrictLifecycleServlet.java:313)
    # at com.ibm.ws.webcontainer.servlet.StrictLifecycleServlet.service(StrictLifecycleServlet.java:116)
    # at com.ibm.ws.webcontainer.servlet.ServletInstance.service(ServletInstance.java:283)
    # at com.ibm.ws.webcontainer.servlet.ValidServletReferenceState.dispatch(ValidServletReferenceState.java:42)
    # at com.ibm.ws.webcontainer.servlet.ServletInstanceReference.dispatch(ServletInstanceReference.java:40)
    # at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.handleWebAppDispatch(WebAppRequestDispatcher.java:978)
    # at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.dispatch(WebAppRequestDispatcher.java:564)
    # at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.forward(WebAppRequestDispatcher.java:200)
    # at com.mayco.mvc.MVCServlet.processRequest(MVCServlet.java:426)
    # at com.mayco.ldap.MayServlet.service(MayServlet.java:415)
    # at com.ibm.ws.webcontainer.servlet.StrictServletInstance.doService(StrictServletInstance.java:110)
    # at com.ibm.ws.webcontainer.servlet.StrictLifecycleServlet._service(StrictLifecycleServlet.java:174)
    # at com.ibm.ws.webcontainer.servlet.IdleServletState.service(StrictLifecycleServlet.java:313)
    # at com.ibm.ws.webcontainer.servlet.StrictLifecycleServlet.service(StrictLifecycleServlet.java:116)
    # at com.ibm.ws.webcontainer.servlet.ServletInstance.service(ServletInstance.java:283)
    # at com.ibm.ws.webcontainer.servlet.ValidServletReferenceState.dispatch(ValidServletReferenceState.java:42)
    # at com.ibm.ws.webcontainer.servlet.ServletInstanceReference.dispatch(ServletInstanceReference.java:40)
    # at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:76)
    # at com.mayco.cy.filter.AuthenticateFilter.doFilter(AuthenticateFilter.java:167)
    # at com.ibm.ws.webcontainer.filter.FilterInstanceWrapper.doFilter(FilterInstanceWrapper.java:132)
    # at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:71)
    # at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.handleWebAppDispatch(WebAppRequestDispatcher.java:974)
    # at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.dispatch(WebAppRequestDispatcher.java:564)
    # at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.forward(WebAppRequestDispatcher.java:200)
    # at com.ibm.ws.webcontainer.srt.WebAppInvoker.doForward(WebAppInvoker.java:119)
    # at com.ibm.ws.webcontainer.srt.WebAppInvoker.handleInvocationHook(WebAppInvoker.java:276)
    # at com.ibm.ws.webcontainer.cache.invocation.CachedInvocation.handleInvocation(CachedInvocation.java:71)
    # at com.ibm.ws.webcontainer.srp.ServletRequestProcessor.dispatchByURI(ServletRequestProcessor.java:182)
    # at com.ibm.ws.webcontainer.oselistener.OSEListenerDispatcher.service(OSEListener.java:334)
    # at com.ibm.ws.webcontainer.http.HttpConnection.handleRequest(HttpConnection.java:56)
    # at com.ibm.ws.http.HttpConnection.readAndHandleRequest(HttpConnection.java:618)
    # at com.ibm.ws.http.HttpConnection.run(HttpConnection.java:439)
    # at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:672)
    I tried setting up a clean environment (server, EAR, web project), but haven't been able to re-solve the problem I had with the original project yet.  If I could get a starting point to look for how to solve this type of error it would be greatly appreciated!                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    I checked my JDK compliance (1.4) and the installed JREs (Standard VM; WebSphere v5.1 EE JRE; C:\Program Files\IBM\WebSphere Studio\Application Developer\v5.1.2\runtimes\base_v51_stub\java\jre)
    I did notice that it was using the JRE System LIbrary [WebSphere v5.1 JRE] and I changed it to the WebSphere v5.1 EE JRE like I think it should have been...
    and the web server startup begins with:
    *** Starting the server ***
    ************ Start Display Current Environment ************
    WebSphere Platform 5.1 [BASE 5.1.0.3 cf30412.02] [JDK 1.4.1 b0344.02] running with process name localhost\localhost\server1 and process id 2692
    Host Operating System is Windows XP, version 5.1
    Java version = J2RE 1.4.1 IBM Windows 32 build cn1411-20031011 (JIT enabled: jitc), Java Compiler = jitc, Java VM name = Classic VM
    was.install.root = C:\Program Files\IBM\WebSphere Studio\Application Developer\v5.1.2\runtimes\base_v51
    user.install.root = C:\Program Files\IBM\WebSphere Studio\Application Developer\v5.1.2\runtimes\base_v51
    Java Home = C:\Program Files\IBM\WebSphere Studio\Application Developer\v5.1.2\runtimes\base_v51\java\jre
    ws.ext.dirs = C:\Program Files\IBM\WebSphere Studio\Application Developer\v5.1.2\runtimes\base_v51/java/lib;C:\Program Files\IBM\WebSphere Studio\Application Developer\v5.1.2\runtimes\base_v51/classes;C:\Program Files\IBM\WebSphere Studio\Application Developer\v5.1.2\runtimes\base_v51/classes;C:\Program Files\IBM\WebSphere Studio\Application Developer\v5.1.2\runtimes\base_v51/lib;C:\Program Files\IBM\WebSphere Studio\Application Developer\v5.1.2\runtimes\base_v51/lib/ext;C:\Program Files\IBM\WebSphere Studio\Application Developer\v5.1.2\runtimes\base_v51/web/help;C:\Program Files\IBM\WebSphere Studio\Application Developer\v5.1.2\runtimes\base_v51/deploytool/itp/plugins/com.ibm.etools.ejbdeploy/runtime;C:/Program Files/IBM/SQLLIB/java/db2java.zip;C:/Program Files/IBM/WebSphere Studio/Application Developer/v5.1.2/wstools/eclipse/plugins/com.ibm.etools.webservice_5.1.2/runtime/worf.jar
    Classpath = C:\Program Files\IBM\WebSphere Studio\Application Developer\v5.1.2\runtimes\base_v51/properties;C:\Program Files\IBM\WebSphere Studio\Application Developer\v5.1.2\runtimes\base_v51/properties;C:\Program Files\IBM\WebSphere Studio\Application Developer\v5.1.2\runtimes\base_v51/lib/bootstrap.jar;C:\Program Files\IBM\WebSphere Studio\Application Developer\v5.1.2\runtimes\base_v51/lib/j2ee.jar;C:\Program Files\IBM\WebSphere Studio\Application Developer\v5.1.2\runtimes\base_v51/lib/lmproxy.jar;C:\Program Files\IBM\WebSphere Studio\Application Developer\v5.1.2\runtimes\base_v51/lib/urlprotocols.jar;C:\WebSphere\properties;C:\spi4j2.5.4_J2ee1.4\clientLib\XEES.jar;C:\spi4j2.5.4_J2ee1.4\clientLib\bcprov-jdk14-139.jar;C:\spi4j2.5.4_J2ee1.4\clientLib\config.jar;C:\spi4j2.5.4_J2ee1.4\clientLib\spi4jStub_2.5.4.jar;C:\spi4j2.5.4_J2ee1.4\clientLib\XEES100J.jar;C:\spi4j2.5.4_J2ee1.4\clientLib\XEES110J.jar;C:\spi4j2.5.4_J2ee1.4\clientLib\XEES120J.jar;C:\spi4j2.5.4_J2ee1.4\clientLib\XEES200J.jar;C:\spi4j2.5.4_J2ee1.4\clientLib\XTCP211.jar;C:\spi4j2.5.4_J2ee1.4\Demo\log4j-1.2.8.jar;C:\spi4j2.5.4_J2ee1.4\coreLib\spi4jCore_2.5.4.jar;C:\spi4j2.5.4_J2ee1.4\coreLib\axis-1.1.jar;C:\spi4j2.5.4_J2ee1.4\coreLib\xmlParserAPIs-2_2_1.jar;C:\spi4j2.5.4_J2ee1.4\coreLib\jaxrpc.jar;C:\spi4j2.5.4_J2ee1.4\coreLib\wsdl4j.jar;C:\spi4j2.5.4_J2ee1.4\coreLib\fsgWsif1.1.jar;C:\spi4j2.5.4_J2ee1.4\Demo\commons-logging.jar;C:\spi4j2.5.4_J2ee1.4\coreLib\tools.jar;C:\spi4j2.5.4_J2ee1.4\coreLib\commons-pool-1.2.jar;C:\spi4j2.5.4_J2ee1.4\coreLib\saaj.jar;C:\spi4j2.5.4_J2ee1.4\coreLib\commons-beanutils-core.jar;C:\spi4j2.5.4_J2ee1.4\coreLib\commons-collections-3.1.jar;C:\spi4j2.5.4_J2ee1.4\coreLib\commons-discovery.jar;C:\spi4j2.5.4_J2ee1.4\coreLib\commons-lang-2.1.jar;C:\spi4j2.5.4_J2ee1.4\coreLib\connector.jar;C:\spi4j2.5.4_J2ee1.4\coreLib\FEDRWSCHECKSTATUSAxisInfo.jar;C:\spi4j2.5.4_J2ee1.4\coreLib\fscontext.jar;C:\spi4j2.5.4_J2ee1.4\coreLib\IFSClassLoader1.2.jar;C:\spi4j2.5.4_J2ee1.4\coreLib\j2ee1.4.jar;C:\spi4j2.5.4_J2ee1.4\coreLib\jca.jar;C:\spi4j2.5.4_J2ee1.4\coreLib\jta.jar;C:\spi4j2.5.4_J2ee1.4\coreLib\mail.jar;C:\spi4j2.5.4_J2ee1.4\coreLib\providerutil.jar;C:\spi4j2.5.4_J2ee1.4\coreLib\qname.jar;C:\spi4j2.5.4_J2ee1.4\coreLib\soaprmi-1_1.jar;C:\spi4j2.5.4_J2ee1.4\coreLib\xalan.jar;C:\spi4j2.5.4_J2ee1.4\coreLib\xercesImpl-2_2_1.jar;C:/Program Files/IBM/WebSphere Studio/Application Developer/v5.1.2/wstools/eclipse/plugins/com.ibm.etools.websphere.tools.common_5.1.1.1/runtime/wteServers.jar;C:/Program Files/IBM/WebSphere Studio/Application Developer/v5.1.2/wstools/eclipse/plugins/com.ibm.etools.websphere.tools.common_5.1.1.1/runtime/wasToolsCommon.jar
    Java Library path = C:\Program Files\IBM\WebSphere Studio\Application Developer\v5.1.2\runtimes\base_v51/bin;C:\Program Files\IBM\WebSphere Studio\Application Developer\v5.1.2\runtimes\base_v51/java/bin;C:\Program Files\IBM\WebSphere Studio\Application Developer\v5.1.2\runtimes\base_v51/java/jre/bin;C:\Program Files\IBM\WebSphere Studio\Application Developer\v5.1.2\eclipse\jre\bin;.;C:\Program Files\IBM\WebSphere Studio\Application Developer\v5.1.2\eclipse\jre\bin;C:\oracle\product\10.2.0\client_2\bin;C:\oracle\product\10.2.0\client_1\bin;Y:\oracle\ora92\BIN;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\PROGRA~1\CA\SHARED~1\SCANEN~1;C:\PROGRA~1\CA\ETRUST~1;C:\PROGRA~1\IBM\SQLLIB\BIN;C:\PROGRA~1\IBM\SQLLIB\FUNCTION;C:\Program Files\Microsoft SQL Server\80\Tools\BINN;C:\Program Files\Rational\common;C:\Program Files\Rational\ClearCase\bin;C:\Program Files\IBM\SDP70\jdk\bin
    ************* End Display Current Environment *************

  • Bouncing Ball without Main Method

    Hi. I needed to reserch on the Internet sample code for a blue bouncing ball which I did below. However, I try coding a main class to start the GUI applet and it's not working. How can I create the appropriate class that would contain the main method to start this particular application which the author did not provide? The actual applet works great and matches the objective of my research (http://www.terrence.com/java/ball.html). The DefaultCloseOperation issues an error so that's why is shown as remarks // below. Then the code in the Ball.java class issues some warning about components being deprecated as shown below. Thank you for your comments and suggestions.
    Compiling 2 source files to C:\Documents and Settings\Fausto Rivera\My Documents\NetBeansProjects\Rivera_F_IT271_0803B_01_PH3_DB\build\classes
    C:\Documents and Settings\Fausto Rivera\My Documents\NetBeansProjects\Rivera_F_IT271_0803B_01_PH3_DB\src\Ball.java:32: warning: [deprecation] size() in java.awt.Component has been deprecated
        size = this.size();
    C:\Documents and Settings\Fausto Rivera\My Documents\NetBeansProjects\Rivera_F_IT271_0803B_01_PH3_DB\src\Ball.java:93: warning: [deprecation] mouseDown(java.awt.Event,int,int) in java.awt.Component has been deprecated
      public boolean mouseDown(Event e, int x, int y) {
    2 warnings
    import javax.swing.*;
    public class BallMain {
    * @param args the command line arguments
    public static void main(String[] args) {
    Ball ball = new Ball();
    //ball.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    ball.setSize( 500, 175 ); // set frame size
    ball.setVisible( true ); // display frame
    import java.awt.*;*
    *import java.applet.*;
    import java.util.Vector;
    // Java Bouncing Ball
    // Terrence Ma
    // Modified from Java Examples in a Nutshell
    public class Ball extends Applet implements Runnable {
    int x = 150, y = 100, r=50; // Position and radius of the circle
    int dx = 8, dy = 5; // Trajectory of circle
    Dimension size; // The size of the applet
    Image buffer; // The off-screen image for double-buffering
    Graphics bufferGraphics; // A Graphics object for the buffer
    Thread animator; // Thread that performs the animation
    boolean please_stop; // A flag asking animation thread to stop
    /** Set up an off-screen Image for double-buffering */
    public void init() {
    size = this.size();
    buffer = this.createImage(size.width, size.height);
    bufferGraphics = buffer.getGraphics();
    /** Draw the circle at its current position, using double-buffering */
    public void paint(Graphics g) {
    // Draw into the off-screen buffer.
    // Note, we could do even better clipping by setting the clip rectangle
    // of bufferGraphics to be the same as that of g.
    // In Java 1.1: bufferGraphics.setClip(g.getClip());
    bufferGraphics.setColor(Color.white);
    bufferGraphics.fillRect(0, 0, size.width, size.height); // clear the buffer
    bufferGraphics.setColor(Color.blue);
    bufferGraphics.fillOval(x-r, y-r, r*2, r*2); // draw the circle
    // Then copy the off-screen buffer onto the screen
    g.drawImage(buffer, 0, 0, this);
    /** Don't clear the screen; just call paint() immediately
    * It is important to override this method like this for double-buffering */
    public void update(Graphics g) { paint(g); }
    /** The body of the animation thread */
    public void run() {
    while(!please_stop) {
    // Bounce the circle if we've hit an edge.
    if ((x - r + dx < 0) || (x + r + dx > size.width)) dx = -dx;
    if ((y - r + dy < 0) || (y + r + dy > size.height)) dy = -dy;
    // Move the circle.
    x += dx; y += dy;
    // Ask the browser to call our paint() method to redraw the circle
    // at its new position. Tell repaint what portion of the applet needs
    // be redrawn: the rectangle containing the old circle and the
    // the rectangle containing the new circle. These two redraw requests
    // will be merged into a single call to paint()
    repaint(x-r-dx, y-r-dy, 2*r, 2*r); // repaint old position of circle
    repaint(x-r, y-r, 2*r, 2*r); // repaint new position of circle
    // Now pause 50 milliseconds before drawing the circle again.
    try { Thread.sleep(50); } catch (InterruptedException e) { ; }
    animator = null;
    /** Start the animation thread */
    public void start() {
    if (animator == null) {
    please_stop = false;
    animator = new Thread(this);
    animator.start();
    /** Stop the animation thread */
    public void stop() { please_stop = true; }
    /** Allow the user to start and stop the animation by clicking */
    public boolean mouseDown(Event e, int x, int y) {
    if (animator != null) please_stop = true; // if running request a stop
    else start(); // otherwise start it.
    return true;
    }

    FRiveraJr wrote:
    I believe that I stated that this not my code and it was code that I researched.and why the hll should this matter at all? If you want help here from volunteers, your code or not, don't you think that you should take the effort to format it properly?

  • How can i call a main method  from a different class???

    Plzz help...
    i have 2 classes.., T1 and T2.. Tt2 is a class with a main method....i want to call the main method in T2......fromT1..is it possibl..plz help

    T2.main(args);

  • How to add a code TestIfElse(10) to the Main method of the Program.cs class?

    How to add a code  TestIfElse(10) to the Main method of the Program.cs class?
    Here is my code and I have copied from the Wiley book for Microsoft certification page 14,
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    namespace ifelse_Statement
        class Program
            static void Main(string[] args);
            TestIfElse(10);
            public static void TestIfElse(int n);
            if(n < 10)
                     Console.WriteLine("n is less than 10");
             else if(n < 20)
                    Console.WriteLine("n is less than 20");
             else if(n < 30)
                Console. WriteLine("n is greater than or equal to 30");
    Here is the error list I am getting,
    Error 1      Method must have a return type        C:\Users\PVS\documents\visual studio 2013\Projects\Lesson01\switch_Statement\Program.cs
    12 13
    switch_Statement
    Error 2
    Type expected C:\Users\PVS\documents\visual studio 2013\Projects\Lesson01\switch_Statement\Program.cs
    12 24
    switch_Statement
    Error 3
    Method must have a return type C:\Users\PVS\documents\visual studio 2013\Projects\Lesson01\ifelse_Statement\Program.cs
    12 9
    ifelse_Statement
    Error 4
    Type expected C:\Users\PVS\documents\visual studio 2013\Projects\Lesson01\ifelse_Statement\Program.cs
    12 20
    ifelse_Statement
    Error 5
    Invalid token 'if' in class, struct, or interface member declaration
    C:\Users\PVS\documents\visual studio 2013\Projects\Lesson01\ifelse_Statement\Program.cs
    16 9
    ifelse_Statement
    Error 6
    Invalid token '10' in class, struct, or interface member declaration
    C:\Users\PVS\documents\visual studio 2013\Projects\Lesson01\ifelse_Statement\Program.cs
    16 16
    ifelse_Statement
    Error 7
    Type expected C:\Users\PVS\documents\visual studio 2013\Projects\Lesson01\ifelse_Statement\Program.cs
    16 16
    ifelse_Statement
    Error 8
    Invalid token '(' in class, struct, or interface member declaration
    C:\Users\PVS\documents\visual studio 2013\Projects\Lesson01\ifelse_Statement\Program.cs
    18 35
    ifelse_Statement
    Error 9
    A namespace cannot directly contain members such as fields or methods
    C:\Users\PVS\documents\visual studio 2013\Projects\Lesson01\ifelse_Statement\Program.cs
    20 10
    ifelse_Statement
    Error 10
    Type or namespace definition, or end-of-file expected
    C:\Users\PVS\documents\visual studio 2013\Projects\Lesson01\ifelse_Statement\Program.cs
    30 1
    ifelse_Statement
    Error 11
    The type or namespace name 'n' could not be found (are you missing a using directive or an assembly reference?)
    c:\users\pvs\documents\visual studio 2013\projects\lesson01\ifelse_statement\program.cs
    16 12
    ifelse_Statement
    Error 12
    'System.Console.WriteLine(string, params object[])' is a 'method' but is used like a 'type'
    c:\users\pvs\documents\visual studio 2013\projects\lesson01\ifelse_statement\program.cs
    18 26
    ifelse_Statement

    static void Main(string[] args){
    TestIfElse(10);
    public static void TestIfElse(int n)
    if (n < 10)
    Console.WriteLine("n is less than 10");
    else if (n < 20)
    Console.WriteLine("n is less than 20");
    else if (n < 30)
    Console.WriteLine("n is greater than or equal to 30");
    Fouad Roumieh

  • Class extending a Frame with main method in it - how do I use the methods?

    Howdy.
    Having a problem.. I want my "main" class, ie. the class with the main method in it to extend a Frame class.. because the main method is static, I can't use Frame's methods.
    What's a trick to get around this ? I am making a deliberate design decision to extend the Frame class, because I thought it was.. well.. better. I could always just create a Frame object and utilise it.. but from little things I've read and seen it's better to extend it.
    When I use Forte to make a Frame program it sets up a constructor/etc. for the main class and then it does something akin to this (the class is called MazeGenerator) :
    public static void main(String args[]) {
    new MazeGenerator().show();
    What does "new MazeGenerator().show();" do when it's not being associated to an object handle ??
    Ta.
    - Scutt.

    Create an instance of the frame in main then the constructor can control it. Or you could add an init method or something:
    class MyFrame extends Frame {
    public static void main (String [] args) {
    MyFrame frame = new MyFrame();
    frame.init();
    You don't necessarily have to have a reference to an Object in order to create one. All the work can be done in the constructor (something I'm not really fond of however)

  • Calling main method in another class using command line arguements

    Hi
    My program need to use 4 strings command line arguments
    entered in Project properties/Run/Application Parameters
    java programming for beginners // arguments
    The program needs to call main in the second class 4 times using argument 1 the first call, argument 2 the second call on so on.
    So the output wil be
    java
    programming
    for
    beginners
    import java.lang.*;
    public class First extends Second{
      public static void main(String[] args) {
        for(int i = 0; i < args.length; i++){
           Second.main(args); // Error I think
    import java.lang.*;
    public class Second {
    public static void main(String[] args){
    System.out.println(args[0]);
    "First.java": Error #: 300 : method main(java.lang.String) not found in class Second at line 6, column 15
    I am only a beginner with little knowledge of java so can the code be as basic as possible

    Your style looks quite bad for starters..... Hows
    this://import java.lang.*; /* NOT NEEDED */
    public class First extends Second{
    public First(String s) {
    super(s);
    public static void main(String[] args) {
    for(int i = 0; i < args.length; i++){
    new First(s);
    public class Second {
    public Second(String s)
    System.out.println(s);
    NOT NEEDED:
    public static void main(String[] args){
    System.out.println(args[0]);
    }My question to you: Do you understand why my code
    works? (does it do what you want?)I think since this is some kind of lesson, the OP have to implement some way to use the main method of the Second class as it is, that is, with String[] args. I think this lesson is interesting exactly because of this requirenment. But, anyway, I don�t know, that is just my assumption...

  • Does not contain a static 'Main' method suitable for an entry point_

    Hello
    I want to to do a project with Entiity Framework . I add a project to my solution for my domain class and it's name is 'LinkModel.DomainClasses'.  when I prees F5 there is an error like bellow.
    Could You help me to solve this? thanks alot
    ..\Documents\Training\LinkCodeFirstLast\LinkCodeFirst\LinkCodeFirst\LinkModel.DomainClasses\obj\Debug\LinkModel.DomainClasses.exe'
    does not contain a static 'Main' method suitable for an entry point

    Hi bkshn,
    This error is caused by the missing "Main" method in your project. it is the entry point of your project.
    If you want to create a EF project, you could follow the way in the aricle below.
    https://msdn.microsoft.com/en-us/data/ee712907#codefirst
    The Main method is like below.
    class Program
    static void Main(string[] args)
    using (var db = new BloggingContext())
    // Create and save a new Blog
    Console.Write("Enter a name for a new Blog: ");
    var name = Console.ReadLine();
    var blog = new Blog { Name = name };
    db.Blogs.Add(blog);
    db.SaveChanges();
    // Display all Blogs from the database
    var query = from b in db.Blogs
    orderby b.Name
    select b;
    Console.WriteLine("All blogs in the database:");
    foreach (var item in query)
    Console.WriteLine(item.Name);
    Console.WriteLine("Press any key to exit...");
    Console.ReadKey();
    And you could start to learn the EF from the following MSDN blogs.
    https://msdn.microsoft.com/en-us/data/ee712907
    If you have any other concern regarding this issue, please feel free to let me know.
    Best regards,
    Youjun Tang
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Projectname.exe' does not contain a static 'Main' method suitable for an entry point .

    Hi,
    I'm developing a blog reader for windows 8 store app. It was perfectly worked before. But because of some miss behave my coding i get below error. No other errors there.
    Error    1    Program 'c:\Users\.........\Desktop\Blog_Reader\Blog_Reader\obj\Release\intermediatexaml\Blog_Reader.exe' does not contain a static 'Main' method suitable for an entry point    C:\Users\..........\Desktop\Blog_Reader\Blog_Reader\CSC  
     Blog_Reader
    Please help me to figure this.
    Thank You!

    Go to your App.Xaml and R-Click Go to Properties
    Check whether the Build Action is ApplicationDefinition
    If not change it to ApplicationDefinition. Clean the code (solution ) and Deploy..
    Chears....

Maybe you are looking for

  • Is there a way to turn the iPad off without using the power button?

    I have the new iPad air. LOVE IT! One thing though...I have a folio style cover on it, magnet closure = power off. The case does not allow for power button access, and there are times when I wish for a way to power it off without closing that cover.

  • Color Management Discrepencies Between Bridge, ACR & Photoshop

    Hi - I've had a color management issue I can't wrap my head around which is similar to this infamous thread: http://forums.adobe.com/message/3235601#3235601 I'm hoping with a little more information provided I can get this figured out. The basic prob

  • What is proper syntax for using PassBack in a Report page select statement

    In my select statement I reference the passBack function using: onClick="javascript:passBack()" In my Page Header I (Typically) define the passBack function as: <script language="JavaScript" type="text/javascript"> function passBack(passVal1,passVal2

  • Sleep Help...Question

    Hi All, My girlfriend and I just got ipods, Two 30gig videos 1Black and 1White. We both used the 1-10-2006 updater and are at version 1.1 Her Black Ipod has "Sleep" in the main menu and mine(white) does not. I already read the Sleep timer documentati

  • DS 6.3.1 slow searches

    We have a relatively large installation (16 million entries in multiple db-s) with Solaris 10 x64 running on HP BL460c quad core intel machines. Our problem is, that the system is fast in 99.9% of the time (bind+search: 0.01s), but sometimes we get a