Das Problem Sie haben den Import ist, dass Sie die String-Array deklarieren und instanziieren müssen, bevor Sie selbst wissen, wie viele Elemente darin sein werden (da Sie nicht, wie viele Strings wissen würde nicht enthalten Sie "e", bevor Sie die Schleife durchlaufen. Wenn Sie eine ArrayList verwenden, müssen Sie die erforderliche Größe nicht kennen. Hier ist mein Code von Anfang bis Ende.
Zeichenfolge [] theWords = {"Hallo", "Auf Wiedersehen", "Morgen"};
//creating a new ArrayList object
ArrayList<String> myList = new ArrayList<String>();
//adding the corresponding array contents to the list.
//myList and theWords point to different locations in the memory.
for(String str : theWords) {
myList.add(str);
}
//create a new list containing the items you want to remove
ArrayList<String> removeFromList = new ArrayList<>();
for(String str : myList) {
if(str.contains("e")) {
removeFromList.add(str);
}
}
//now remove those items from the list
myList.removeAll(removeFromList);
//create a new Array based on the size of the list when the strings containing e is removed
//theWords now refers to this new Array.
theWords = new String[myList.size()];
//convert the list to the array
myList.toArray(theWords);
//now theWords array contains only the string(s) not containing 'e'
System.out.println(Arrays.toString(theWords));
Blick in: 1) unter Verwendung von Arraylisten, nicht-Arrays, und 2) die String 'enthält (...)' Verfahren. –
Warum verwenden Sie 'ArrayList' nicht? Wenn es Ihre Aufgabe ist, Arrays zu verwenden, dann sollten Sie 'contains' verwenden, um nach' character' oder 'word' zu suchen. –
Ich habe ArrayList noch nicht in der Klasse gelernt und Array ist für mich noch relativ neu. –