2012-02-29 44 views
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); 
    } 
}  

回答

3

我知道問題出在while循環的性質,因爲它會成長,然後添加[&hellip;]

不是。問題在於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可以複製陣列的速度一樣快;但總的來說,這是設計動態調整大小陣列的最佳方式。)

+0

我該如何修改我的代碼以「分別跟蹤其長度」?我剛剛看到一篇解釋效率的維基百科文章,現在我很好奇。 – 2012-02-29 23:28:38

+1

@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

+0

優秀的代碼!我已經做了一些代碼來修剪操作結束時數組中額外的非填充索引。非常感謝!我現在完全理解,用「邏輯」和實際長度=) – 2012-03-01 00:08:20