在不知道数组大小的情况下输入数组 [英] Enter array without knowing its size

查看:179
本文介绍了在不知道数组大小的情况下输入数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以在Java中创建数组,而无需先定义或要求其长度?

Is there a way to make an array in Java, without defining or asking for its length first?

又名用户输入一些数字作为参数,然后程序创建了一个包含这么多参数的数组.

A.k.a the user enters some numbers as arguments, and the program creates an array with that many arguments.

推荐答案

有没有一种方法可以在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.

目前还不清楚您处于什么情况.如果您知道在执行时而不是在编译时的数组长度,那很好:

It's unclear exactly what situation you're in. If you know the array length at execution time but not at compile time, that's fine:

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的数组.

and it will create an array of length 5.

如果您真的在创建数组之前不知道数组的长度,例如,是否要询问用户元素,然后让他们输入完成某些特殊值后,您可能希望使用某种List,例如ArrayList.

If you really don't know the length of the array before you need to create it - for example, if you're going to ask the user for elements, and then get them to enter some special value when they're done, then you would probably want to use a List of some kind, such as 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<Integer> list = new ArrayList<>();
        while (true) {
            int input = scanner.nextInt();
            if (input == 0) {
                break;
            }
            list.add(input);
        }
        System.out.println("You entered: " + list);
    }    
}

可以然后根据实际需要将该List转换为数组,但理想情况下,您可以继续将其用作List.

You can then convert that List into an array if you really need to, but ideally you can just keep using it as a List.

这篇关于在不知道数组大小的情况下输入数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆