1

I am creating a class Perfect inside the main class and in Perfect class i am creating a method perf() and i want to call this method in the main method..how to do it?

My code is here

public class Fib {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub


            }

    class Perfect {

        void perf(){
            int sum = 0;
            int count = 0;

            for(int i=6; i<=10000; i++){
                for(int j=1; j<=i/2; j++){
                    if(i%j==0){
                        sum+=j;
                    }
                }
                if(sum==i){
                    count=count+1;
                    System.out.println(i);
                }
                sum=0;
            }

            System.out.println("Total perfect number is : "+count);

        }
    }
}

3 Answers3

3

new Fib().new Perfect().perf() should work fine

Toon Borgers
  • 3,638
  • 1
  • 14
  • 22
0

You can write in this form

    Fib outer = new Fib();
    Perfect inner = outer.new Perfect (); 
    System.out.println(inner.perf());
Danyal
  • 360
  • 1
  • 12
  • did you try to compile that code? perf() returns void, nothing "printable" by System.out.println(), just take off that System.out.println() – morgano Feb 14 '14 at 13:30
0

You can call inner class method inside the main method.

you have to make inner class as static, then you can directly access by className.MethodName(). There is not a necessity of creating object..

Example:

package com;

public class Fib {
    public static void main(String[] args) {
        Perfect.assign(5);
       }

   private static class Perfect {      
       static void assign(int i) {
           System.out.println("value i : "+i);
       }

    }
}

Here, Perfect is inner class, assign is a method which is place inside inner class... Now i just call inner class method by className.MethodName().

When you run this program you will get an Output: value i : 5

Hope this helps.!!

Wanna Coffee
  • 2,742
  • 7
  • 40
  • 66