首页 > 编程知识 正文

scanner输入数组 不知道长度,java创建数组

时间:2023-05-03 09:51:45 阅读:9298 作者:1773

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 : )列表;

}

}

然后,可以根据需要将列表转换为数组,但理想情况下可以继续用作列表。

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。