作为家庭作业的一部分,我们应该创建一个数组,如果用户试图向超出范围的新索引输入更多数据,该数组将自动调整大小。我们不允许使用任何库,如hashsets,arraylist等。我的代码可以工作,然而,数组的长度总是比所需的长度大一。我知道问题出在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);
}
} 发布于 2012-03-01 07:09:41
我知道问题出在while循环的性质上,因为它会增长,然后添加…
不用谢。问题出在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复制数组的速度一样快;但一般来说,这是设计可动态调整大小的数组的最佳方法。)
https://stackoverflow.com/questions/9507986
复制相似问题