如何在java中的for循环中创建数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22319669/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to create array inside for loop in java
提问by Prasanth
I want to create 10 arrays inside a for
loop, using the names 1, 2, 3, ..., 10 for the arrays.
我想在for
循环中创建 10 个数组,使用名称 1, 2, 3, ..., 10 作为数组。
I tried like this, but it's not working:
我试过这样,但它不工作:
int n = 10;
for(int i = 0; i < n; i++)
{
String [] i = new String[];
}
回答by Mc Kevin
you can't declare a variable with leading numbers.
您不能声明带有前导数字的变量。
回答by Scary Wombat
In you code i
is already defined within the scope of the for
loop.
Also as soon as you exit the loop, the created variables will be out of scope.
在你的代码i
中已经定义了for
循环范围内。此外,一旦退出循环,创建的变量将超出范围。
Furthermore, variables beginning with an Integer are invalid in Java.
此外,以整数开头的变量在 Java 中无效。
回答by Kumar Abhinav
回答by Khaled.K
int n = 10;
int m = 5;
String[][] arrayOfArrays = new String[n][];
for(int i=0;i<n;i++)
{
arrayOfArrays[i] = new String[m];
}
回答by MjZac
You can use ArrayList
for creating an array of array, else go for a 2D String
array.
您可以ArrayList
用于创建数组数组,否则请使用二维String
数组。
ArrayList<String[]> x = new ArrayList<String[]>();
int n =10;
for(int i=0;i<n;i++){
x.add(new String[5]);
}
回答by Sky
you might want to use a 2D array which might offers what you need.
您可能想要使用可能提供您需要的二维数组。
Read this Syntax for creating a two-dimensional array
阅读此语法以创建二维数组
String [][] test = new String [10][10];
It is as if the first [] can be your 'i' like what you required, and the 2nd [] can be what you need to store the variable. It is normally use for cases like if you need an "array of array", meaning 100x array.
就好像第一个 [] 可以是你的“i”,就像你需要的一样,第二个 [] 可以是你需要存储变量的东西。它通常用于诸如需要“数组数组”之类的情况,这意味着 100x 数组。