2

I am trying to get parameter from cmd and pass that parameter to method Fibonacci, but I am getting some error. Can anyone tell me why I am getting this error?

Thank you.

Code:

class fibo {

static void Fibonacci(int Total,int n1,int n2){

    if(Total > 1){      
        int sum = n1 + n2;
        System.out.print(sum + " ");
        n1 = n2;
        n2 = sum;
        --Total;
        Fibonacci(Total,n1,n2);
    }
}

}

class main{

    public static void main(String args[]){

    fibo f = new fibo();    
    System.out.print(0 + " ");
    System.out.print(1 + " ");
    int Total = args[0];
    int n1 = args[1];
    int n2 = args[2];    
    f.Fibonacci(Total,n1,n2);


    }
}

Error:

fibonacci.java:26: error: incompatible types: String cannot be converted to int
int Total = args[0];

fibonacci.java:27: error: incompatible types: String cannot be converted to int

    int n1 = args[1];

fibonacci.java:28: error: incompatible types: String cannot be converted to int

int n2 = args[2];

3 errors
kiyah
  • 1,502
  • 2
  • 18
  • 27
sachin dubey
  • 755
  • 9
  • 28

1 Answers1

6
int n1 = args[1];
int n2 = args[2]; 

You are trying to assign String to int directly. No, that won't work.

args is String array and it contains Strings. So when you try to assign a value from it to an integer varaible you should convert.

For ex :

int n1 = Integer.parseInt(args[1]);

Same with other assignments as well.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307