nihero
nihero

Reputation: 27

How to call a static method from main class?

I got this code:

public static ArrayList<Integer> MakeSequence(int N){

    ArrayList<Integer> x = new ArrayList<Integer>();

    if (N<1) {
        return x; // need a null display value?
    }
    else {
        for (int j=N;j>=1;j--)  {
            for (int i=1;i<=j;i++) {
                x.add(Integer.valueOf(j));
            }
        }
    return x;
    }
}       

I am trying to call it from the main method just like this:

System.out.println(MakeSequence (int N)); 

but I get an error...

Any recommendations? Much appreciated, thanks!

Upvotes: 0

Views: 140

Answers (3)

Farrukh Shahzad
Farrukh Shahzad

Reputation: 51

The first issue is I think that N should be some int value not defining the variable in the method call. Like

int N = 20;
ClassName.MakeSequence(N);

The other issue you will face. As System.out.println() only prints string values and you are passing the ArrayList object to it, so use it like this System.out.println(ClassName.MakeSequence(N).toString())

Upvotes: 2

azro
azro

Reputation: 54168

You define the method as follow MakeSequence (int N), this means that method expects one parameter, of type int, and it'll be called N when use inside the method.

So when you call the method, you need to pass an int like :

MakeSequence(5);
// or
int value = 5;
MakeSequence(value);

Then put all of this in a print or use the result in a variable

System.out.println(MakeSequence(5));
//or
List<Integer> res = MakeSequence(5);
System.out.println(res);

All of this code, to call the method, should be in antoher method, like the main one


  • Change x.add(Integer.valueOf(j)); to x.add(j); as j is already an int

  • to follow Java naming conventions : packages, attributes, variables, parameters, method have to start in lowerCase, while class, interface should start in UpperCase

Upvotes: 4

ILMTitan
ILMTitan

Reputation: 11037

System.out.println(MakeSequence (int N)); 

should be

int N = 5; // or whatever value you wish
System.out.println(MakeSequence (N));

Just pass a variable of the correct type. You don't say that it is an int again;

Upvotes: 4

Related Questions