作爲家庭作業分配的一部分,我們應該創建一個數組,如果用戶嘗試向超出邊界的新索引輸入更多數據,則會調整自身的大小。我們不允許使用像哈希集,陣列列表等任何庫。我的代碼工作,但是,數組的長度總是最終比所需要的大。我知道問題在於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-02-29 23:28:38
@KevinHua:而不是'String [] x = new String [kb.nextInt()];',你會寫'int length = kb.nextInt(); String [] x = new String [length];'。 (這樣你就可以記住最初指定的最小長度。)然後,在你的'while'循環之後,你可以添加'if(index> length){length = index; }(因爲,如果/一旦你超出了最初指定的最小長度,'index'就是每次迭代後的邏輯長度)。最後,在你的程序結束時,你會改變'for(int i = 0; i
ruakh
2012-02-29 23:33:27
優秀的代碼!我已經做了一些代碼來修剪操作結束時數組中額外的非填充索引。非常感謝!我現在完全理解,用「邏輯」和實際長度=) – 2012-03-01 00:08:20