Results 1 to 4 of 4
  1. #1
    jhuwalker is offline Member
    Join Date
    Jan 2011
    Posts
    7
    Rep Power
    0

    Default Pass Compiler, but Not Run. ?Exception in thread "main" ?

    /* A Method called Factorial
    * Using perimater in Main function
    * to pass some variable to Factorial
    * Return a Factorial Vaule to main
    */


    public class FactorialMath{
    private static final int MAX_Num=4; // What is 4! (4*3*2*1)

    public void main(String[] args){
    for (int i=0; i<MAX_Num; i++) {
    System.out.println(i +"!=" + Factorial(i));
    }
    }

    private int Factorial(int n) {
    int result = 1;
    for (int i=1; 1<=n; i++){
    result *=i;
    }
    return result;
    }
    }

    === Result===
    D:\java-code>javac FactorialMath.java

    D:\java-code>java FactorialMath
    Exception in thread "main" java.lang.NoSuchMethodError: main

  2. #2
    Petr's Avatar
    Petr is offline Senior Member
    Join Date
    Jan 2011
    Location
    Russia
    Posts
    620
    Rep Power
    4

    Default

    You have mistake in construction main methods
    public static void main(String[] arg)
    only same way.
    Skype: petrarsentev
    http://TrackStudio.com

  3. #3
    jhuwalker is offline Member
    Join Date
    Jan 2011
    Posts
    7
    Rep Power
    0

    Default Did that, but won't compiled

    D:\MyData\MyEdu\ComputerLanguage\Java\java-code>javac FactorialMath.java
    FactorialMath.java:13: non-static method Factorial(int) cannot be referenced from a static context
    System.out.println(i +"!=" + Factorial(i));
    ^
    1 error

  4. #4
    Iron Lion is offline Senior Member
    Join Date
    Nov 2010
    Posts
    210
    Rep Power
    5

    Default

    As the compiler says, you can't call a non-static method from a static one. You have two choices: you can make factorial() a static method, or you can call it from a non-static method. The latter is considered better practice.

Similar Threads

  1. Replies: 5
    Last Post: 06-22-2010, 04:51 PM
  2. Replies: 1
    Last Post: 11-20-2009, 08:58 PM
  3. Replies: 6
    Last Post: 07-16-2009, 04:30 PM
  4. Replies: 1
    Last Post: 07-16-2009, 11:35 AM
  5. Replies: 1
    Last Post: 08-07-2007, 08:10 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •