gpt4 book ai didi

java - 动态数组算法

转载 作者:行者123 更新时间:2023-11-29 06:02:51 24 4
gpt4 key购买 nike

作为家庭作业的一部分,我们应该创建一个数组,如果用户尝试向超出范围的新索引输入更多数据,该数组将自行调整大小。我们不允许使用任何库,如 hashsets、arraylists 等。我的代码可以工作,但是,数组的长度最终总是比所需的大 1。我知道问题在于 while 循环的性质,因为它会增长然后添加,但我不知道如何解决它。

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Scanner;
public class DynamicArray
{
public static void main(String[] args)
{
Scanner kb = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
System.out.print("Enter a desired length for an array: ");
String[] x = new String[kb.nextInt()];
int index = 0;
System.out.print("Enter as many Strings as desired, separated by a new line. Type in \"end\" to print out the contents of the array.");
String input = kb.nextLine();
while(!input.equalsIgnoreCase("end"))
{
if (index < x.length)
{
x[index] = input;
}
else
{
String[] temp = new String[x.length + 1];
for (int i = 0; i < x.length; ++i)
{
temp[i] = x[i];
}
temp[index] = input;
x = temp;
}
++index;
input = kb.nextLine();
}
for (int i = 0; i < x.length; ++i)
{
System.out.println(x[i]);
}
System.out.println(x.length);
}
}

最佳答案

I know the problem lies in the nature of the while loop because it will grow and then add […]

完全没有。问题在于 Scanner.nextInt()Scanner.nextLine() 的工作方式。 Scanner.nextInt() 将读入一个整数,但不会吞下整数后的换行符。所以 Scanner.nextLine() 看到的第一件事就是那个换行符,它认为它看到了一个空行,这就是它返回的内容。所以 x[0] 是一个空字符串。

如果你改变这个,你可以更清楚地看到这一点:

            System.out.println(x[i]);

为此:

            System.out.println(i + ": " + x[i]);

因为那时你会看到它打印的第一件事是 0:

顺便说一句,您的方法通常效率很低,因为它需要创建比实际需要更多的数组。与其将数组的大小增加一个,不如将数组的大小加倍并分别跟踪其长度(而不是使用 x.length). (不可否认,在你的情况下,效率可能不是问题,因为你正在从用户那里获取输入,并且用户不可能在任何地方以 Java 复制数组的速度输入元素;但总的来说,这是设计可动态调整大小的数组的最佳方式。)

关于java - 动态数组算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9507986/

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