java 在不知道其大小的情况下输入数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28381956/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 13:29:24  来源:igfitidea点击:

Enter array without knowing its size

javaarrays

提问by Miroslav Trifonov

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

有没有办法在 Java 中创建一个数组,而不需要先定义或询问它的长度?

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

也就是用户输入一些数字作为参数,程序会创建一个包含这么多参数的数组。

回答by Jon Skeet

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.

有没有办法在 java 中创建一个数组,而不先定义或要求它的长度?也就是用户输入一些数字作为参数,程序会创建一个包含这么多参数的数组。

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);
    }
}

You can run that as:

您可以将其运行为:

java Test 5

and it will create an array of length 5.

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

If you reallydon'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 Listof some kind, such as ArrayList.

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

For example:

例如:

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);
    }    
}

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

如果确实需要,您可以将其List转换为数组,但理想情况下,您可以继续将其用作List.

回答by Mike Nakis

You need to use an ArrayList for this.

为此,您需要使用 ArrayList。

EDIT:

编辑:

Miroslav is most probably a student trying to complete an assignment. Usually in these assignments you are asked to read values from standard input and do something with them. In this case, store them in an array. So, at the time he has a value to store in the array, he does not know yet how many values are coming. So, ArrayList is the way to go.

米罗斯拉夫很可能是一个试图完成作业的学生。通常在这些作业中,您会被要求从标准输入中读取值并对其进行处理。在这种情况下,将它们存储在一个数组中。所以,当他有一个值要存储在数组中时,他还不知道有多少值即将到来。所以,ArrayList 是要走的路。

回答by user3437460

Is there a way to make an array in java, without defining or asking for it's length first ?

Is there a way to make an array in java, without defining or asking for it's length first ?

Yes, it is possible in Java. This is not possible in C++ though. C++ requires the size of the array to be determined at compile time.

是的,这在 Java 中是可能的。但这在 C++ 中是不可能的。C++ 要求在编译时确定数组的大小。

In Java you can create new arrays at run time.

在 Java 中,您可以在运行时创建新数组。

int[] array; //Create a reference of int array (no arrays created yet)

//Prompt for size..
Scanner scn = new Scanner(System.in);
System.out.println("Enter size of array;")
int size = scn.nextInt();

array = new int[size]; //this is allowed in Java


Some additional information:

一些附加信息:

Take note that arrays are fixed size. Once the size is determined (even at run time) you cannot change it anymore. However there is a work-around solution if you want to "expand" the array size.

请注意,数组是固定大小的。一旦确定大小(即使在运行时),您就无法再更改它。但是,如果您想“扩展”数组大小,则有一个变通的解决方案。

//continuing from above coding example..
array = new int[newSize];

Doing this will point arrayto a new array. So if you want to keep the values of the old array, you have to manually copy the old array elements to the new array. However, this is not efficient.

这样做将指向array一个新数组。因此,如果要保留旧数组的值,则必须手动将旧数组元素复制到新数组中。但是,这效率不高。

An efficient way to grow and shrink your array size is to use Listor ArrayList. But to answer your question alone on arrays. Yes, you can create it at run time and you can also point your array reference to another array at run time also.

增大和缩小数组大小的一种有效方法是使用ListArrayList。但是要单独在阵列上回答您的问题。是的,您可以在运行时创建它,也可以在运行时将数组引用指向另一个数组。

回答by PrathiSaiHarika

Yes, I have read both the arr element and the corresponding space followed by it.

是的,我已经阅读了 arr 元素和它后面的相应空格。

And when encountered newline(\n), stopped reading the input further.

当遇到换行符(\n)时,停止进一步读取输入。

int main()
{
char temp;
int arr[100];
int j = 0;

while (1)
{
    scanf("%d%c", &arr[j++], &temp);
    if (temp == '\n')
        break;
}
printf("%d", j);
}

So. here j is specifying the array size. Hope, I could answer your question.

所以。这里 j 指定数组大小。希望,我可以回答你的问题。

Have a good day.

祝你有美好的一天。

回答by deadLock

I think you are looking for this.

我想你正在寻找这个。

I read it sometime earlier on StackOverflow only.

我早些时候只在 StackOverflow 上读过它。

import java.util.Arrays;
import java.util.Scanner;

public class temp
{
    public static void main(String[] args)
    {
        Scanner sc=new Scanner(System.in);

        int[] array=Arrays.stream(sc.nextLine().split("\s+")).mapToInt(Integer::parseInt).toArray();

        System.out.println(Arrays.toString(array));

        sc.close();
    }
}

//Input- 123 414 42 452 1 2

//输入- 123 414 42 452 1 2

//Output- 123 4144 42 452 1 2

//输出- 123 4144 42 452 1 2

回答by Vitalii Bandura

ArrayList is probably the best structure in this situation when you only need to add elements. If you want to add/delete elements from middle of Collection use LinkedList instead.

当您只需要添加元素时,ArrayList 可能是这种情况下的最佳结构。如果要从 Collection 中间添加/删除元素,请改用 LinkedList。