我正在尝试制作一个程序,它不会询问用户值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
}
}
你可以只使用已经存在的不断增长的集合,例如ArrayList
、LinkedList
等。您可以根据需要添加任意数量的元素,它们负责动态分配必要的空间。
这
称为动态调整大小,具有摊销复杂度O(n)。主要思想是每次数组已满时将数组大小加倍。有关实现细节,我会看看这里。
PS:不要忘记将您的问题的一些答案标记为已解决,因为您似乎从未这样做过。