Is there a way to make an array in java,withoutdefiningoraskingforit’slengthfirst? a.k.atheuserenterssomenumbersasarguments,andtheprogramcreatesanarraywiththatmanyarguments。
目前的状态尚不清楚。 如果知道运行时的数组长度而不是编译时的数组长度,则可以执行以下操作:
公共类测试{
publicstaticvoidmain (字符串[ ] args ) {
int length=integer.parseint (args [0];
string [ ] array=new string [ length ];
system.out.println (createdanarrayoflength : ) Array.Length );
}
}
您可以执行以下操作:
java Test 5
将创建长度为5的数组。
如果在创建之前不知道数组的长度,例如,要询问用户元素,并在完成时输入特殊值,也可以使用ArrayList等列表。
例如:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
公共类测试{
publicstaticvoidmain (字符串[ ] args ) throws Exception { )。
sanner scanner=new scanner (system.in;
system.out.println (enter numbers,with 0 to end );
列表列表=new ArrayList (;
while (真)。
int input=scanner.nextInt (;
if(input==0) {
布雷克;
}
list.add (输入;
}
system.out.println (you entered : )列表;
}
}
然后,可以根据需要将列表转换为数组,但理想情况下可以继续用作列表。