简体   繁体   中英

How to pass value to a method using object created in main class in Java

I am preparing a program of fibonacci series using recursion and memoization but I am not able to pass value to that method using object.Can anyone point me out what is wrong with my code

class fib_mem
{
  int f []=new int[10];
  int fibmem(int n)
  {
    if(n<1)
    {
      f[n]=n;
      return n;
    }
    else
    {
      if(f[n-2]==-1)
      {
        f[n-2]=fibmem(n-2);
      }
      if(f[n-1]==-1)
      {
        f[n-1]=fibmem(n-1);
      }
      f[n]=f[n-2]+f[n-1];
      return f[n-2]+f[n-1];
    }
  }
}
class abc
{
  public static void main(String[] args) {
  fib_mem obj=new fib_mem(5);
  int a=obj.fibmem();
  System.out.println(""+a);
  }
}

Use below code for class abc:

class abc
{
  public static void main(String[] args) {
  // creating an object using constructor
  fib_mem obj=new fib_mem();

  // sending 5 as an argument to the method fib_mem
  int a=obj.fibmem(5);
  System.out.println(""+a);
  }
}

The number 5 should be passed as in method - fib_mem() but not in the constructor - fib_mem obj=new fib_mem(5); as you did.

Here is some code that might help you write your own recursion. I dont think an inner class is needed for this. Try naming your variables so that just by their names you can figure out what they do.

public class Main {

    static boolean stop = false;
    static int counter = 0;

    public static void main(String[] args) {

        System.out.print(0 + " ");
        System.out.print(1 + " ");

        printFiboRecursive(0,1);
    }

    static void printFiboRecursive(int a, int b){

        if(counter > 10){
            stop = true;
        }

        if(stop != true){
            System.out.print(a+b + " ");
            counter++;
            int para1 = b;
            int para2 = a+b;
            printFiboRecursive(para1,para2);
        }
    }
}

Here I created simple to read code displaying fibonacci's sequence for you. Hope it helps you create your own. Class has been replaced with a static method and it is not recursive.

public class Main {

    public static void main(String[] args) {

        printFibonacciSequence(5);
    }

    static void printFibonacciSequence(int amount){
        int a=0;
        int b=1;
        int temp=0;

        System.out.print(a + " ");
        System.out.print(b + " ");

        for(int i=0 ; i< (amount-2) ; i++){
            temp = a+b;
            System.out.print(temp + " ");
            a=b;
            b=temp;
        }
    }
}

Output will be:

0 1 1 2 3 

Change the method's parameter in main for more numbers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM