2015-10-17 65 views
0

我真的很困擾這個問題的一部分。我一直在觀看視頻幾個小時,並在網上進行研究,但我似乎無法正確理解。我需要生成一個for循環來檢查字符串是否爲meg,並將其移除並移動剩餘的元素。這不是一個數組列表。從數組中刪除重複的字符串

寫第二,傳統的for循環來檢查字符串「 梅格 」各自 元件,如果 陣列中找到,將其刪除,移位剩餘元素,並顯示名稱的數組。

我知道我的循環會在我的最後一個客戶名稱&之間用於打印它。我只是對接下來要做的事感到困惑。

這裏是我當前的代碼:

public class CustomerListerArray { 
    public static void main(String[] args) { 
     String customerName[] = new String[7]; 
     customerName[0] = "Chris"; 
     customerName[1] = "Lois"; 
     customerName[2] = "Meg"; 
     customerName[3] = "Peter"; 
     customerName[4] = "Stewie"; 
     for (int i = customerName.length - 1; i > 3; i--) { 
      customerName[i] = customerName[i - 2]; 
     } 
     customerName[3] = "Meg"; 
     customerName[4] = "Brian"; 
     for (String name: customerName) { 
      System.out.println(name); 
     } 
    } 
} 

回答

0

跟着你已經給出的說明,你可以嘗試這樣的:

int max = customerName.length; 
for (int i = 0; i < max; i++) { // Traditional for loop 
    if ("Meg".equals(customerName[i]) { // Look for the name "Meg" 
     // If found, shift the array elements down one. 
     for (int j = i; j < (max - 1); j++) { 
      customerName[j] = customerName[j+1]; 
     } 
     i--; // Check the i'th element again in case we just move "Meg" there. 
     max--; // Reduce the size of our search of the array. 
    } 
} 

一旦做到這一點,你可以在結果迭代和打印陣列:

for (int i = 0; i < max; i++) { 
    System.out.println(customerName[i]); 
} 
+0

'equalsIgnoreCase' ?? – sam

+0

@ sam2090在關於不區分大小寫的搜索的問題中沒有任何內容,但是如果需要,這當然可以完成。 – dave

+0

其實nvm。發現我做錯了什麼。 – BlueJay

0

的想法是遍歷你的數組的所有索引,並檢查他們是否等於"Meg"。如果不是這種情況,索引的值將連接到StringBuilder對象。

最後,我們採用我們的StringBuilder對象字符串的值,並將它與我們放在名稱之間的額外空格分開。

我們終於有了我們新的String陣列與所需的大小。

public static void main(String[] args) { 
    String customerName[] = new String[7]; 
    customerName[0] = "Chris"; 
    customerName[1] = "Lois"; 
    customerName[2] = "Meg"; 
    customerName[3] = "Peter"; 
    customerName[4] = "Stewie"; 
    customerName[5] = "Meg"; 
    customerName[6] = "Brian"; 
    StringBuilder names = new StringBuilder(); 
    for (String name: customerName) { 
     if (!name.equals("Meg")) names.append(name + " "); 
    } 
    String[] myNewArray = names.toString().split(" "); 
    System.out.println(Arrays.toString(myNewArray)); 
} 

輸出:

[Chris, Lois, Peter, Stewie, Brian] 
+0

'equalsIgn oreCase'? – sam

+0

@ sam2090否=>「字符串」Meg「的每個元素」 –