Array | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Array

eg; String[] names={"Jason ","Chris","Tina","Lisa"}; How do i declare a method that will remove from the name Chris from the Array. Then once you removed the name, how do i declare another method displaying the length of the array now that a name has been removed? For the removing of the name, heres my code(its running but no output); public void Remove(String[]Array){ int i=0; while(Array[i].equals("chris")){ Array[i]=null; System.out.println(Array) public static void main(String[]args){ Question4 Remove1=new Question4(); Remove1.Remove(names); } The idea behind my method is that the loop goes through the array until it finds the name "chris". Then once it finds the name, it sets it to null(deleting it).

17th Apr 2017, 4:09 PM
Mogammad Shameer Losper
Mogammad Shameer Losper - avatar
3 Answers
+ 1
use arraylist instead. ArrayList<String> list = new ArrayList<String>(Arrays.asList(array)); list.remove(list.indexOf("chris")); String[] newArray = list.toArray(new String[0]); practically, don't use array at all when creating a dynamic list. always use ArrayList.
17th Apr 2017, 4:44 PM
Nikunj Arora
Nikunj Arora - avatar
+ 1
Thank you, i copied and pasted the code lol, Thats why some code is missing as i didnt copy the code properly.
17th Apr 2017, 4:45 PM
Mogammad Shameer Losper
Mogammad Shameer Losper - avatar
0
I think you forgot some parentheses and code in the remove method. Anywho, because the array is now PARTIALLY filled you must keep a variable to keep track of the size. Once something is removed, decrement that variable. example: String[] array = {"a"}; int arrayLength = array.length; //inside remove method Remove(String[] arr){ arrayLength--; // once removed } If you do not want a partially filled array you would need to return a new array that does not contain that name. (So it's remove). While deep-copying all the other elements into the new array. @Nikunj Towards your last statement, if performance is an actual worry you likely wouldn't use an ArrayList. (Of course it wouldn't be an issue in this case, just in general)
17th Apr 2017, 4:37 PM
Rrestoring faith
Rrestoring faith - avatar