gpt4 book ai didi

java - 是否可以使用 while 循环创建一个具有动态内存的数组,而不询问用户内存的大小?

转载 作者:行者123 更新时间:2023-11-30 04:14:19 24 4
gpt4 key购买 nike

我正在尝试编写一个程序,它不会询问用户值 i,其中 i 是数组的元素数量,( int[] someArray = new int[i])。 我面临的两个问题,第一是程序如何自动定位内存大小,第二个问题是,面临不同类型数据的麻烦(我知道这个问题很简单,但无法将逻辑放在一起)。 基本上我的程序结构如下:

Scanner input = new Scanner(System.in);

int[] someArray;
int element;
String order;

while(!("done").equals(order=input.nextLine())){

if(some integer){

//set the user input as the value of array element, and change the pointer to the next element
}

if(some string other than "done"){

System.out.println();
//continues the loop

}


}

最佳答案

您可以只使用已经存在的不断增长的集合,例如ArrayListLinkedList等。您可以添加任意数量的元素,它们会负责动态分配必要的空间。

关于java - 是否可以使用 while 循环创建一个具有动态内存的数组,而不询问用户内存的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18783228/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com