簡體   English   中英

將對象數組傳遞給java中的方法

[英]Passing an array of objects to a method in java

大家好,我有一個問題。 當我嘗試將對象數組傳遞給方法時出現錯誤 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
   }

很抱歉這篇很長的帖子......

findMaxPos 是您的類 staticMethod 的靜態方法。

當您不在定義它的類中調用靜態函數時,您需要使用之前的類名調用它:

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.
}

請注意,在 java 中,約定是給類一個以大寫字母開頭的名稱(以小寫字母開頭的名稱是給實例的)。

好吧,上述解決方案應該可行,但除此之外,還有一些其他事項需要考慮。

  1. public Object(int a,) 構造函數不完整。
  2. max = name[0], pos = 0 中缺少分號(;)
  3. 最重要的是 max 和 Pos 的返回類型是未定義的。 PO 可以是 int 但變量 max 應該是 Object 類型。
  4. 如果 max 的返回類型是 object,則不能使用 (name[i] >max ),因為它未針對對象類型定義。 糾正這些錯誤,希望您的代碼能夠正常運行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM