在Java中返回数组 [英] Returning Arrays in Java

查看:138
本文介绍了在Java中返回数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我完全不知道为什么这段代码不会返回数组...我觉得我的编译器有问题:

I have absolutely no idea as to why this code won't return an array... I feel like there is a problem with my compiler:

public class trial1{

    public static void main(String[] args){
        numbers();
    }

    public static int[] numbers(){
        int[] A = {1,2,3};
        return A;
    }
}

代码根本不返回任何内容。这让我疯狂!

The code returns nothing at all. It's driving me crazy!

推荐答案

它返回数组,但所有返回的东西(包括一个数组)都是这样的:返回值。在你的情况下,你得到 numbers()的值,这恰好是一个数组(它可能是任何东西,你仍然会有这个问题),只是让它坐在那里。

It is returning the array, but all returning something (including an Array) does is just what it sounds like: returns the value. In your case, you are getting the value of numbers(), which happens to be an array (it could be anything and you would still have this issue), and just letting it sit there.

当一个函数返回任何东西时,它实质上是替换它被调用的行(在你的情况下: numbers() ; )带有返回值。那么,你的 main 方法实际上是在执行以下操作:

When a function returns anything, it is essentially replacing the line in which it is called (in your case: numbers();) with the return value. So, what your main method is really executing is essentially the following:

public static void main(String[] args) {
    {1,2,3};
}

当然,这似乎什么都不做。如果你想用返回值做一些事情,你可以这样做:

Which, of course, will appear to do nothing. If you wanted to do something with the return value, you could do something like this:

public static void main(String[] args){
    int[] result = numbers();
    for (int i=0; i<result.length; i++) {
        System.out.print(result[i]+" ");
    }
}

这篇关于在Java中返回数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆