将数组值传递给单独的方法

时间:2013-09-05 13:14:05

标签: java arrays methods return

在main方法中读取5个整数值的数组。创建一个单独的函数,确定哪个数字最大。将最大值返回到main并在main中打印。 我启动了代码,但我的问题是我不知道如何将我在main方法中读取的值(数组值)传递给函数! 我这样开始:

import java.util.*;
public class arraybiggest {
    public static int main (String[]args) {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter 5 values: ");
        int [] x = new int[5];
        for (int i=0; i<5; i++) {
            x[i] = in.nextInt();
            return x;
        }
    }
    public static int  passarray(int [ ] value) {

    }
}

请帮助我!谢谢!

4 个答案:

答案 0 :(得分:1)

您可以调用您的函数并将数组传递给它,如下所示:

passarray(x);

但首先你需要从循环中删除return x;

答案 1 :(得分:0)

import java.util.*;
public class arraybiggest {

   public static int main (String[]args) {
          Scanner in = new Scanner(System.in);
          System.out.println("Enter 5 values: ");
          int [] x = new int[5];
          for (int i=0; i<5; i++) {
             x[i] = in.nextInt();           
         }

         int result = passarray(x);
         System.out.println("the biggest number is:" +result );
   }


  public static int  passarray(int [ ] value) {
        int result=value[0]
        for(int i=1;i<value.length;i++){
            if (value[i] > result) {
                result= value[i];
            }
        }
       return result;
   }
}

答案 2 :(得分:0)

for (int i=0; i<5; i++) {
        x[i] = in.nextInt();
        }
 passarray(x);

答案 3 :(得分:0)

    import java.util.*;
    public class arraybiggest {
        public static int main (String[]args) {
            Scanner in = new Scanner(System.in);
            System.out.println("Enter 5 values: ");
            int [] x = new int[5];
            for (int i =0; i<5; i++) {
                x[i] = in.nextInt();
            }
            System.out.println(findMax(x));
        }
        public static int  findMax(int [ ] value) {
            int max = value[0];
            for (int i = 1; i < value.length; i++) {
                if (value[i] > max) {
                    max = value[i];
                }
            }
            return max;
        }

    }