简体   繁体   English

如何使用二维数组作为输入?

[英]How to use a 2D Array as input?

So I'm currently supposed to write a method that takes a 2D Array as input and return a 1D Array.所以我目前应该编写一个以二维数组作为输入并返回一维数组的方法。 The problem is that I have trouble inputting a 2D Array to even test what I want to do.问题是我无法输入二维数组来测试我想要做什么。

That is the method.这就是方法。

public static int[] flatten (int[][] input)

flatten(null);

When I try to insert an example this is what it is supposed to look like: flatten([[1,2,3],[4,5,6]])当我尝试插入一个示例时,它应该是这样的: flatten([[1,2,3],[4,5,6]])

But then I get the error that "the left hand of an assignment must be a variable"?但是后来我得到了“赋值的左手必须是一个变量”的错误?

To pass a 2D Array as the input you should write it like this要将 2D 数组作为输入传递,您应该这样写

int[][] input = {{1, 2, 3}, {4, 5, 6}};
int[] output = flatten(input);

or或者

int[] output = flatten(new int[][] {{1, 2, 3}, {4, 5, 6}} );

This is how you would go about giving an argument to that method.这就是您为该方法提供参数的方式。

flatten(new int[][] { { 1, 2, 3 }, { 1, 2, 3 } });

In Java 1D array definitions can be expressed without the need to use the new int[]{...} syntax, although it is still possible.在 Java 中,可以在不需要使用new int[]{...}语法的情况下表达一维数组定义,尽管它仍然是可能的。

int[] someArray = { 1, 2, 3 }; // Perfectly valid
int[] someArray = new int[]{ 1, 2, 3 }; // Equally valid

However, 2D array definitions need to be explicitly stated when given as arguments to methods, in this way.但是,以这种方式作为方法的参数提供时,需要明确说明二维数组定义。

int[][] someArray = { { 1, 2, 3 }, { 1, 2, 3 } }; // Valid
flatten(someArray); // Valid
flatten(new int[][]{ { 1, 2, 3 }, { 1, 2, 3 } }); // Valid
flatten({ { 1, 2, 3 }, { 1, 2, 3 } }) // Invalid!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM