简体   繁体   English

如何从主类调用静态方法?

[英]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: 我试图像这样从main方法调用它:

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

but I get an error... 但我得到一个错误...

Any recommendations? 有什么建议吗? Much appreciated, thanks! 非常感谢,谢谢!

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; 您不必再说它是一个int了;

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. 您按照MakeSequence (int N)定义方法,这意味着该方法需要一个int类型的参数,并且在该方法内部使用时将其称为N

So when you call the method, you need to pass an int like : 因此,当您调用该方法时,您需要传递一个int像:

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

Then put all of this in a print or use the result in a variable 然后将所有这些内容print或在变量中使用结果

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 所有这些要调用该方法的代码都应该在另一个方法中,就像main方法一样


  • Change x.add(Integer.valueOf(j)); 更改x.add(Integer.valueOf(j)); to x.add(j); x.add(j); as j is already an int 因为j已经是一个int

  • to follow Java naming conventions : packages, attributes, variables, parameters, method have to start in lowerCase , while class, interface should start in UpperCase 遵循Java命名约定:包,属性,变量,参数,方法必须在lowerCase中开始,而类,接口应该在UpperCase中开始

The first issue is I think that N should be some int value not defining the variable in the method call. 第一个问题是我认为N应该是一些int值,而不是在方法调用中定义变量。 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()) 由于System.out.println()仅打印字符串值,并且您正在将ArrayList对象传递给它,因此像这样使用它System.out.println(ClassName.MakeSequence(N).toString())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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