Void mains

Please help, I have just about had enough of this code for my lifetime.
I am trying to get a timer running in the background that fires an event every minute.
I had the code:
public class Apl
    public static void main(String argv[])
        boolean gui = true;
        int portNum = 110;
        //server object
     POP3Server server;
        //user mailset
        Set mailSet = new HashSet();
        .  //does some stuff
}So i try and modify it to do this
e.g
public class Apl
    public static void main(String argv[])
        boolean gui = true;
        int portNum = 110;
        //server object
     POP3Server server;
        //user mailset
        Set mailSet = new HashSet();
        .  //does some stuff
        TimerTask fetchMail  = new FetchMail();
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(fetchMail, 1, 10000);
    public class FetchMail()
        System.out.println("HI");
}In the hope it would print HI every 10 seconds. But no.
Any ideas? Thanks

Still having problems with this timer. I have had a rethink about what I want to do with it and am still having problems.
private String makeMailDrop()
        String users = "";
        String thisLine;
        //DOES SOME STUFF HEREThen from another class
public POP3Server(int port, POP3ServerFrame frame, Set mailSet)
         //vars
          this.port = port;
          this.frame = frame;
          this.mailSet = mailSet;
          gui=true;
                uidlArr = new String[100];
                counter = 1;
          //timer
          //makeTimer();
          output("Initializing..this may take a while..\n");
                output("Welcome To Highway42 POP3 Server. \n\n");
                makeMailDrop();
                TimerTask loopMD = makeMailDrop();
                Timer timer = new Timer();
                timer.scheduleAtFixedRate(loopMD, 1, 10000);The problem being that the types are different, loopMD is a TimerTask and I am trying to assign it to a methiod that returns a string.
so I tried TimerTask loopMD = makeMailDrop();and then it says it cant find makeMailDrop().
How would I implement this so on the timer it runs makeMailDrop()
Thanks

Similar Messages

  • How to call java with public static void main(String[] args) throws by jsp?

    how do i call this from jsp? <%spServicelnd temp = new spServicelnd();%> does not work because the program has a main. can i make another 2nd.java to call this spServiceInd.java then call 2nd.java by jsp? if yes, how??? The code is found below...
    import java.net.MalformedURLException;
    import java.io.IOException;
    import com.openwave.wappush.*;
    public class spServiceInd
         private final static String ppgAddress = "http://devgate2.openwave.com:9002/pap";
         private final static String[] clientAddress = {"1089478279-49372_devgate2.openwave.com/[email protected]"};
    //     private final static String[] clientAddress = {"+639209063665/[email protected]"};
         private final static String SvcIndURI = "http://devgate2.openwave.com/cgi-bin/mailbox.cgi";
         private static void printResults(PushResponse pushResponse) throws WapPushException, MalformedURLException, IOException
              System.out.println("hello cze, I'm inside printResult");
              //Read the response to find out if the Push Submission succeded.
              //1001 = "Accepted for processing"
              if (pushResponse.getResultCode() == 1001)
                   try
                        String pushID = pushResponse.getPushID();
                        SimplePush sp = new SimplePush(new java.net.URL(ppgAddress), "SampleApp", "/sampleapp");
                        StatusQueryResponse queryResponse = sp.queryStatus(pushID, null);
                        StatusQueryResult queryResult = queryResponse.getResult(0);
                        System.out.println("Message status: " + queryResult.getMessageState());
                   catch (WapPushException exception)
                        System.out.println("*** ERROR - WapPushException (" + exception.getMessage() + ")");
                   catch (MalformedURLException exception)
                        System.out.println("*** ERROR - MalformedURLException (" + exception.getMessage() + ")");
                   catch (IOException exception)
                        System.out.println("*** ERROR - IOException (" + exception.getMessage() + ")");
              else
                   System.out.println("Message failed");
                   System.out.println(pushResponse.getResultCode());
         }//printResults
         public void SubmitMsg() throws WapPushException, IOException
              System.out.println("hello cze, I'm inside SubmitMsg");          
              try
                   System.out.println("hello cze, I'm inside SubmitMsg (inside Try)");                         
                   //Instantiate a SimplePush object passing in the PPG URL,
                   //product name, and PushID suffix, which ensures that the
                   //PushID is unique.
                   SimplePush sp = new SimplePush(new java.net.URL(ppgAddress), "SampleApp", "/sampleapp");
                   //Send the Service Indication.
                   PushResponse response = sp.pushServiceIndication(clientAddress, "You have a pending Report/Request. Please logIn to IRMS", SvcIndURI, ServiceIndicationAction.signalHigh);
                   //Print the response from the PPG.
                   printResults(response);
              }//try
              catch (WapPushException exception)
                   System.out.println("*** ERROR - WapPushException (" + exception.getMessage() + ")");
              catch (IOException exception)
                   System.out.println("*** ERROR - IOException (" + exception.getMessage() + ")");
         }//SubmitMsg()
         public static void main(String[] args) throws WapPushException, IOException
              System.out.println("hello cze, I'm inside main");
              spServiceInd spsi = new spServiceInd();
              spsi.SubmitMsg();
         }//main
    }//class spServiceInd

    In general, classes with main method should be called from command prompt (that's the reason for main method). Remove the main method, put the class in a package and import the apckage in your jsp (java classes should not be in the location as jsps).
    When you import the package in jsp, then you can instantiate the class and use any of it's methods or call the statis methods directly:
    <%
    spServiceInd spsi = new spServiceInd();
    spsi.SubmitMsg();
    %>

  • Default access specifiers for void main()

    I m having one problem that if i make void main(String a[])
    syntax like private static void main(String args[]) and run using jdk1.4 it will run. So my question is that why this is possible still i making main() private. If i run it in jdk1.5.0 then it give error main is not public so what was the problem with the jdk1.4?

    Congratulations on your first post after almost 2
    years. ?The most impressive thing is that he remembered his
    password ...I posted by first message in 2004, I only used this account to read the bugdatabase and vote on bugs prior to that. So I don't see anything strange in having an account, and not using the forums.
    Kaj
    Ps. But I'm also impressed by the fact that he remembered the password, I had an account which I created in -97, but I forgot the password to that account :(

  • Why we use string args[]  in void main()

    why we use string in void main in java?

    Because that's roughly how C did it and Java is based on C.
    You can get all the input arguments using JMX, but it's rather complicated and not useful except in obscure cases.
    (I use it to determine if a unit test is running in debug and change the timeouts in my tests so I can step through a test without it stopping at a random point due to a time out)

  • Why can't created an object in the "public static void main(String args[])"

    Example:
    public Class Exp {
    public static void main(String args[])
    new Exp2();-------------> To Occur Error
    Class Exp2 {
    public Exp2()

    You can't create an inner class within main, because
    it is a static method. Inner classes can only be
    created by true class methods.This is not correct. You can create an inner class object in a static method. You just have to specify an outer class object that the inner class object should be created within:
    Exp2 exp2 = new Exp().new Exp2();

  • Jnlp main class: static void main() or applet class????

    When create jnlp file for applet, I have to specify main class. This "main class", is it the class that contain static void main(), or the applet class. The way I design is the that the applet class will SwingUtilities.InvokeAndWait the "main class".
    Should I specify main class when jar the files or in jnlp file?
    Lastly, when I upload my jnlp file to my web server, and try to access it through a web browser, it keeps saying that the web address is invalid. Do I need any special permission from the web server to run jnlp file?
    Thank you and have a wonderful day

    Subject: jnlp main class: static void main() or applet class????
    Note that one '?' denotes a question, wile two or more often denotes a dweeb.
    yunaeyes wrote:
    When create jnlp file for applet, I have to specify main class. This "main class", is it the class that contain static void main(), or the applet class.That depends on whether the JNLP you did not think to add, declares an [<application-desc>|http://java.sun.com/j2se/1.4.2/docs/guide/jws/developersguide/syntax.html#application_desc] or [<applet-desc>|http://java.sun.com/j2se/1.4.2/docs/guide/jws/developersguide/syntax.html#applet_desc].
    .. The way I design is the that the applet class will SwingUtilities.InvokeAndWait the "main class".
    Should I specify main class when jar the files or in jnlp file?Either way should work, but I prefer in the JNLP file, to avoid the webstart client having to download any Jar(s) eagerly just to look for it.
    Lastly, when I upload my jnlp file to my web server, and try to access it through a web browser, it keeps saying that the web address is invalid. What address, what URL?
    ..Do I need any special permission from the web server to run jnlp file?No. All that is required is that it is accessible, and returns the correct content-type for .jnlp files.
    Thank you and have a wonderful dayIt's bright sunshine, clear skies and a lovely(1) 28 deg. C here, so not going too bad so far. ;)
    (1) Lovely if you are not working in the sun.
    Note that I also offer JaNeLA for comprehensive(2) checking of JNLP launches. Someone at your level of experience with JWS should definitely check it out.
    (2) JaNeLA's checks include validity of JNLP, content-type, resource availability..

  • Standard/common handling void main(String argv[])

    i would like to have a parent class to handle the void main(String argv[]), but I can't instantiate my child class because I dun know it's name.
    any way to get that? or any alternative way to handle the void main(String argv[]) in common? million thanks.
    eg:
    public abstract class parent {
    public static void main(String argv[]){
    // i need to know which child is been run by java childclass
    // so that I can instantiate a new object and call the run method
    public abstract void run();
    public class child1 extends parent{
    public void run(){}
    public class child2 extends parent{
    public void run(){}
    }

    Class.forName(name).newInstance();
    provided I know name=what, right?
    how do I know ppl calling using
    java child1?
    or
    java child2?
    both will go use same
    public static void main(String argv[])
    in parent class.

  • Void main

    Hi,
    Could you please let me know what is wrong with this line please:
    Employee test= new Emp_FT(getId,getFirstName,getLastName,getEmployeeAge,getFullTime);
              public static void main(String args[])  
                         Employee test= new Emp_FT(getId,getFirstName,getLastName,getEmployeeAge,getFullTime);                 
         class Emp_FT extends Employee{
             private String fulltime;
            public Emp_FT( int id, String firstName, String lastName, int employee_age, String address, String ft )
                      super( id, firstName, lastName, employee_age, address);
                        this.fulltime = ft;
                    }Thanks
    Andonny

        public ArrayList parseFile(File input)
            String buffer = null;
            ArrayList data = new ArrayList();
            try
                FileReader fileIn = new FileReader(input);
                BufferedReader bufferIn = new BufferedReader(fileIn);
                buffer = bufferIn.readLine();
                while (buffer != null)
                        //write code here depending on how you arrange your file
                        //store values for name and id in local variables then create
                        //a new employee, if it is a fulltime employee then
                        Emp_FT emp = new Emp_FT(id, first, last, ssn, etc);
                        //or you could create an empoyee first then add the info
                        Emp_FT emp = new Emp_FT();
                        emp.setId(something);
                        emp.setFirstName(something);
                        //then add this employee to your list before proceeding
                        data.add(emp);                    
                    buffer = bufferIn.readLine();
                bufferIn.close();
            catch (IOException e)
                e.printStackTrace();
            return data;
        }

  • Static private void main(String[]) works (?!)

    Did anyone knew that?
    try yourself!!
    public class Foo {
    static private void main (String[] bla) {
       //anything
    }there's even a bug!! And Sun choose not fix it:
    http://developer.java.sun.com/developer/bugParade/bugs/4252539.html
    I'd like to hear what you folks think about this...
    IMO: fuc* encapsulation!

    No, I haven't done the certification exam and I have no plans to. But the answer to that question isstatic public void main (String[] bla)and the fact that other versions happen to work doesn't matter either theoretically or practically. Bugs that appear in certain implementations of Java shouldn't matter.

  • Public static void main

    Hi all
    whether public static void main(String[] a) will execute

    Clem1986 wrote:
    it's an incomplete sentence, it's just a clause; possible endings:
    whether public static void main(String[] a) will execute remains a mystery.*
    whether public static void main(String[] a) will execute is determinable.*
    whether public static void main(String[] a) will execute is propesterous to ponder.*
    whether public static void main(String[] a) will execute is heretical in nature.*
    whether public static void main(String[] a) will execute is not a sentence.*
    Or start clauses,
    _'Tis idiotic to wonder_ whether public static void main(String[] a) will execute.whether public static void main(String[] a) will execute or not, I'm still getting out of my skull tonight

  • Private static void main(String args[]) ... ?????

    even if the main method is declared
    private static void main(String args[])
    //Code Here
    it works fine..can somebody explain the reason behind?

    hi rkippen
    so u mean, since the JVM is calling the main it can
    break all kinds of access specifiers to any class..am
    i right?
    This could be the case.
    However, I tried using 1.4.1 with no development environment (just java.exe) and it gave the following error:
    C:\>java MainTest
    Main method not public.
    So, your development environment might be the cause (e.g. what you use to program your code (e.x. JBuilder)), or the Java version.
    Your development environment might be using reflection to get around Java accessibility checks. For debugging purposes, it is possible to use reflection to obtain refereneces to private methods/fields and invoke those methods and access those fields.
    E.g.
    Vector v = new Vector();
    Field f = v.getClass().getDeclaredField("elementCount");
    f.setAccessible(true); // this is the trick
    f.set(v, new Integer(100));In the presence of a security manager, the setAccessible method will fire a "suppressAccessChecks" permission check.

  • Why main() method has to be void in Java?

    According to the C++ creator Bjarne Stroustrup,
    The definition
            void main() { /* ... */ }
    is not and never has been C++, nor has it even been C.
    See the ISO C++ standard 3.6.1[2]
    Then if Java is developed from C, why the main() method has
    to be void like this:
    Public class JavaClass{
        Public static void main(String[] args){
    }

    First search the forums, you will find a huge thread on this.
    second, to be brief, in C and C++, you have primary thread and when main exits, the application terminates returning a value. e.g. when you do exit(0);
    In java, you could have secondary user-threads (not daemon threads) which you have started in your main and these continue to run even after the main method has exited. So returning a value would not make sense because your application has not terminated as there are still threads running.

  • Why void restriction is there to main() in java

    What if i want to return a static value without creating an instance
    //return TestStatic.getit(); see code below
    What will happen to the value returned by this TestStatic.getit(); see code below
    public class TestStatic {
         private static int x=0;
         public static int getit()
              return x;
         public static void main(String[] args) {
              //System.out.println(TestStatic.getit());
              //return TestStatic.getit();
    TestStatic.getit();
    }

    Calvino
    i think You didn't get my question . i know that it
    cannot return an intyour return statement, even if into comment was ambiguous, then
    but why its return type is void .
    read the answer by LOKO , he has explained it
    correctly .
    one more reason which i found is that , since main is
    static it will be created before main and it will
    have no idea about any method returning any value
    which is going to be created after main.
    2nd point is that we are not expected to call
    /return an value using a static method as java is
    purely an object oriented language and it assumes
    that to do something an object must be there . that
    is the reason the void restriction is there
    static methods may return values... just one example over thousands of other: Integer.parseInt() returns an int value
    java being a object oriented language do not mean that static methods should be void ones everytime
    plus: main is a particular case, so it has to be seen differently from other methods
    Message was edited by:
    Z_skm76

  • How can i invoke a void method in main?

    Hi guys I am killing myself over why we use void method if we can't call on it from main.
    For example i am trying to create a program to calculate military time. In my main i am trying to call setHour which is void. setHour is supose to check if the input of hour is over 24 and if it is i have to reset hour to 00. But it gives an error that i can't call on that method because it is void.
    So how do i invoke it from main?
    and
    Why do we use void if we can't call on it?
    Thanks

    ok here it is mate. It is not finished but pay attention on the setMethods that is what im trying to invoke from main. Here's my methods and then main will be under it.
    public class MilitaryTime
          private int hour;
          private int minute;
          private int second;
           public MilitaryTime()
             hour=0;
             minute=0;
             second=0;
           public MilitaryTime(int hour, int minute, int second)
             this.hour=hour;
             this.minute=minute;
             this.second=second;
           public MilitaryTime(MilitaryTime t)
           public void setHour(int h)
             if(h>=24)
                h=00;
             else
                hour=h;
           public void setMinute(int m)
             if(m>=60)
                m=00;
             else
                minute=m;
           public void setSecond(int s)
             if(s>=60)
                s=00;
             else
                second=s;
           public int getHour()
             return hour;
           public int getMinute()
             return minute;
           public int getSecond()
             return second;
           public void tick()
             second=second+1;
           public String toUniversalString()
             StringBuffer     buffer;
             buffer = new StringBuffer();
          // add the hour (with leading zero if its neccesary)
             if(this.hour < 10)
                buffer.append("0");
             buffer.append(this.hour).append(":");
          // add the minute (with leading zero if its neccesary)
             if(this.minute < 10)
                buffer.append("0");
             buffer.append(this.minute).append(":");
          // add the second (with leading zero if its neccesary)
             if(this.second < 10)
                buffer.append("0");
             buffer.append(this.second).append("");
             return buffer.toUniversalString();
           public String toString()
             StringBuffer     buffer;
             buffer = new StringBuffer();
          // add the hour (with leading zero if its neccesary)
             if(this.hour < 10)
                buffer.append("0");
             buffer.append(this.hour).append(":");
          // add the minute (with leading zero if its neccesary)
             if(this.minute < 10)
                buffer.append("0");
             buffer.append(this.minute).append(":");
          // add the second (with leading zero if its neccesary)
             if(this.second < 10)
                buffer.append("0");
             buffer.append(this.second).append("");
             return buffer.toString();
       }Here is main where i try and call setHour to check for accuracy.
    import javax.swing.*;
    public class TestMilitaryTime
         public static void main(String[]args)
                        String sHour=JOptionPane.showInputDialog(null,
                "Input Hour:", "Military Time",JOptionPane.QUESTION_MESSAGE);
                        int hour=Integer.parseInt(sHour);
                        String sMinutes=JOptionPane.showInputDialog(null,
                "Input minutes:", "Military Time",JOptionPane.QUESTION_MESSAGE);
                        int minutes=Integer.parseInt(sMinutes);
                        String sSeconds=JOptionPane.showInputDialog(null,
                "Input seconds:", "Military Time",JOptionPane.QUESTION_MESSAGE);
                        int seconds=Integer.parseInt(sSeconds);
                        MilitaryTime time= new MilitaryTime(hour,minutes,seconds);
                        System.out.println(time.setHour());
                        System.out.println("The military time is you enterd is "+time.toString());
         Everything else works fine except the setHour thing.
    Thanks

  • Code returns "null" and "0"s in main module - why?

    I am coding a program that is in two modules. The main module serves it's standard function. The inventory class/module has three functions - 1) request stock input on 4 data points (1 String and 3 integers, one of which is a double) - 2) calculate the value of the inventory, and - 3) return string which reads out the 4 data points and the calculation showing the total value of the inventory. I've created the 3 functions in the inventory class/module, but obviously don't have them referring to each other correctly because when we come to the end of the program the output is null for the String and "0"s for the int/doubles. The code is below - any ideas about how to overcome the empty output? The code compiles fine and acts like it is going to work, but when it comes to the final command line it outputs
    "null, which is item number 0, has 0 currently in stock at a price of 0.00 each. The total value of inventory in stock is 0.00"
    Main module:
    public class Main {
        @SuppressWarnings("static-access")
        public static void main(String[] args) {
            Inventory inventory = new Inventory(); //call Inventory class
            inventory.inventoryInput();
            Inventory results = new Inventory();
            results.inventoryResults(); //call for inventoryResults in Inventory class
    }Inventory module:
    import java.util.Scanner;
    import static java.lang.System.out;
    public class Inventory
      //declare and initialize variables
       int itemNumber = 0;
       String productName;
       int stockAmount = 0;
       double productCost = 0;
       double totalValue = 0;
       String inventoryResults;
       //initialize scanner
       Scanner input = new Scanner(System.in);
       public void inventoryInput ()
       out.println("Please enter item number: "); //prompt for item number
          itemNumber = input.nextInt();
       out.println( "Enter product name/description: "); //prompt for product name
          productName = input.next();
       out.println("Quantity in stock: ");
          stockAmount = input.nextInt(); // prompt for stock quantity
       out.println("What is the product cost for each unit? ");
          productCost = input.nextDouble(); // prompt for product cost
        } // end inventoryInput
        public double totalValue( double stockAmount, double productCost )
          totalValue = stockAmount * productCost;
          return totalValue; // return stock value
        } // end totalValue
        public void inventoryResults()
        out.printf("%s, which is item number %d, has %d currently in stock at a " +
         "price of %.2f each. The total value of inventory in stock is " +
         "%.2f\n.", productName, itemNumber, stockAmount, productCost, totalValue);
        } // end inventoryResult
    }// end method

    justStartingOut wrote:
    Actually my final solution was quite simple - I moved the calculation and final formated print text statements into the body of Inventory's class code. It now works. "Works" scares me a bit.
    Someone cooking dinner might rummage about in the fridge and the cupboards to see what's there. Do imaginative things with what they come up with. And, with a bit of luck come up with something tasty or, at any rate edible.
    A physician deciding on a medical treatment would do well to try a more cautious approach. A specific aim would be a good thing. And a calculated appreciation of the documented effects of each medicine. And how they interact.
    It's up to you to determine which approach your coding should resemble. But it seems to me that your original Main class had a perfectly good reason to exist. It was a driver class whose purpose seemed to be to create and use an Inventory. (And using an Inventory is a very different thing from being an Inventory, so it made perfect sense to have two different classes.) To me it works or not, depending on whether it fufills that purpose. And what you have done is not so much solve the problem of it not working, as avoid that problem.
    (If by "moved" you mean that the outputting now occurs as part of - or is called from - inventoryInput() then that is not a good thing. The input method should input: just input.)
    I think that is because once the original input was loaded into the program (when I entered product number, name, price and value), the entries were dropped when the code switched to the next step. I think your intuition is entirely correct. In particular look at what your original main() method does (my comments replacing yours):
    Inventory inventory = new Inventory(); // (A) Create an inventory...
    inventory.inventoryInput(); // ... and put stuff into it
        // (B) Create some new entirely different (and empty) inventory...
    Inventory results = new Inventory();
    results.inventoryResults(); // ... and print its contentsInstead of creating a second inventory, try printing the results of the first one.
    Edited by: pbrockway2 on Apr 22, 2008 12:37 PM
    Whoops ... just read reply 2.
    It might sense, though to call totalValue() at the end your input method (because at that point the total value has changed). Or do away with that method - which you worked on getting right in your other thread ;)

Maybe you are looking for

  • Error when using Home Sharing in iTunes 9

    I'm constantly getting the following error when trying to add songs using the new Home Sharing in iTunes 9. "There was a problem dowloading [song name]. The length received from the server did not match the expected length." Any ideas on why this is

  • My apps won't load after updating to iOS4.3.2. What to do?

    My apps won't load after updating to iOS4.3.2. What to do?

  • Photoshop Elements 10 will not open

    Installing the program went fine, but when I click on the icon on the desktop nothing seems to happen. A background process is started though (the Welcome screen, I think), which I have to go to Task Manager to close. I have never received any error

  • Doubt with raw partition ASM

    Hi Gurus, Have a doubt regarding the raw partitions being used in ASM. 1.Is raw partition being used  only applicable to linux platform , or can it be done on other plaform as well 2.Is it correct if I say if a diskgroup is created with single  raw d

  • Standard Query for Top 10 queries and Users

    Hi Experts, Is there any query which gives the details like , 1. Top 10 queries executed in a month 2. Top 10 users ( By no of queries executed ) Regards, Bhadri M.