[英]Passing an array of objects to a method in java
Hello guys I have a question.大家好,我有一个问题。 I have an error when I am trying to pass an array of object to a method My class
当我尝试将对象数组传递给方法时出现错误 My class
public class Object {
private int x1;
public Object(int a ,){
this.x1=a;
}
public class staticMethods{
public static void findMaxPos(Object[] name){
max = name[0]
pos = 0
for( int i=1; i<name.length ; i++){
if ( name[i] >max ){
max = name[i];
pos = i;
}
}
}
public class Example{
public static void main(String[] args) {
Object[] yp = new Object2[3];
yp[0] = new Object(5);
yp[1] = new Object(6);
yp[2] = new Object(8);
findMaxPos(type)// i get an error of the method findMaxPos is undefined for the type Example
}
So sorry for the long post ...很抱歉这篇很长的帖子......
findMaxPos is a static method of your class staticMethod. findMaxPos 是您的类 staticMethod 的静态方法。
When you are not calling a static function inside the class where it is defined, you need to call it with the name of the class before:当您不在定义它的类中调用静态函数时,您需要使用之前的类名调用它:
public static void main(String[] args) {
Object[] type = new Object2[3];
yp[0] = new Object(5);
yp[1] = new Object(6);
yp[2] = new Object(8);
staticMethods.findMaxPos(type);// This should be ok.
}
Note that in java, the convention is to give classes a name which begin with an uppercase letter (Names which begin with a lowercase letters are given to instances).请注意,在 java 中,约定是给类一个以大写字母开头的名称(以小写字母开头的名称是给实例的)。
Well, the above solution should work but apart from that, there are a couple of other things that need to be taken into consideration.好吧,上述解决方案应该可行,但除此之外,还有一些其他事项需要考虑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.