【问题标题】:Use an array in multiple methods [closed]在多种方法中使用数组[关闭]
【发布时间】:2020-07-04 02:11:00
【问题描述】:

我正在使用 2 种方法创建一个程序。

在第一种方法中,我创建了一个数组,在第二种方法中,我必须显示该数组像一个表格。。 p>

所以我的问题是,我如何在第一种方法中创建一个数组并将其传递给第二种方法进行显示?

public class test {

    public static void main(String[] args) {
        first();
        second();
    }
    public static void first () {
        int N= (int)(Math.random()*5)+1;
        int M= (int)(Math.random()*5)+1;
        int v [][] = new int [N][M];
        for(int i=0; i < v.length; i++) {
            for(int j=0; j < v[0].length; j++) {
                v [i][j]= (int)(Math.random()*5);
            }
        }
    }
    public static void second () {
        for(int i=0; i < v.length; i++) { 
            for(int j=0; j < v[0].length; j++)
                System.out.print(v [i][j] + " ");
            System.out.println("");
        }
    }
}

如何在第二种方法中传递数组“v”?

【问题讨论】:

  • 到目前为止你尝试过什么?你能告诉我们你的代码吗?您是否遇到任何具体错误?
  • 欢迎来到 Stack Overflow。请通过tour 了解 Stack Overflow 的工作原理并阅读How to Ask 或如何提高问题的质量。然后编辑您的问题,以包含您作为minimal reproducible example 的完整源代码,其他人可以对其进行编译和测试。
  • 使用参数和返回值。从这里开始:docs.oracle.com/javase/tutorial

标签: java arrays parameter-passing


【解决方案1】:

如果第一个方法调用第二个方法,直接作为参数传递:

public void doStuff(){
    int[] arr;//initialize
    useArray(arr);
}
public void useArray(int[] arr){
     //use it
}

如果两个方法一个接一个地执行,返回它,保存到一个变量并传递它:

public void outerMethod(){
    int[] arr=createArray();
    useArray(arr);
}
public int[] createArray(){
    int[] arr;
    //initialize it
    return arr;
}
public void useArray(int[] arr){
    //use arr
}

在你的情况下,这将是:

public class test {

    public static void main(String[] args) {
        int[] v=first();
        second(v);
    }
    public static int[][] first () {
        int N= (int)(Math.random()*5)+1;
        int M= (int)(Math.random()*5)+1;
        int v [][] = new int [N][M];
        for(int i=0; i < v.length; i++) {
            for(int j=0; j < v[0].length; j++) {
                v [i][j]= (int)(Math.random()*5);
            }
        }
        return v;
    }
    public static void second (int[][] v) {
        for(int i=0; i < v.length; i++) { 
            for(int j=0; j < v[0].length; j++)
                System.out.print(v [i][j] + " ");
            System.out.println("");
        }
    }
}

[注意事项]

这不仅适用于整数数组,也适用于任何其他数组。

事实上,这适用于任何类型。

按照惯例,类名应该写成 PascalCase,变量(和方法)名应该写成 camelCase。

【讨论】:

  • 谢谢。你是对的。
  • 如果我能帮助你,我会很感激你接受我的回答。
猜你喜欢
  • 1970-01-01
  • 2014-10-18
  • 2021-06-16
  • 2011-08-01
  • 1970-01-01
  • 2021-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多