java求数组输入长度_java-输入数组而不知道其大小

Is there a way to make an array in java, without defining or asking for it’s length first ? A.k.a the user enters some numbers as arguments, and the program creates an array with that many arguments.

目前尚不清楚您所处的状态.如果您知道执行时而不是编译时的数组长度,那就可以了:

public class Test {

public static void main(String[] args) {

int length = Integer.parseInt(args[0]);

String[] array = new String[length];

System.out.println("Created an array of length: " + array.length);

}

}

您可以将其运行为:

java Test 5

它将创建一个长度为5的数组.

如果在创建之前确实不知道数组的长度,例如,如果您要询问用户元素,然后在完成时让他们输入一些特殊值,那么您可能想要使用某种列表,例如ArrayList.

例如:

import java.util.ArrayList;

import java.util.List;

import java.util.Scanner;

public class Test {

public static void main(String[] args) throws Exception {

Scanner scanner = new Scanner(System.in);

System.out.println("Enter numbers, with 0 to end");

List list = new ArrayList<>();

while (true) {

int input = scanner.nextInt();

if (input == 0) {

break;

}

list.add(input);

}

System.out.println("You entered: " + list);

}

}

然后,如果确实需要,可以将该列表转换为数组,但理想情况下,可以继续将其用作列表.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值