Home > Software engineering >  How to remove the last string in an array element using parameters of another method named removeLas
How to remove the last string in an array element using parameters of another method named removeLas

Time:09-15

Here is the question of exercise and my code:

Create the method public static void removeLast(ArrayList strings) in the exercise template. The method should remove the last value in the list it receives as a parameter. If the list is empty, the method does nothing.

public static void main(String[] args) {
    // Try your method in here
    ArrayList<String> arrayList = new ArrayList<>();
    arrayList.add("First");
    arrayList.add("Second");
    arrayList.add("Third");
    System.out.println(arrayList);
    removeLast(arrayList);
    System.out.println(arrayList);
}

public static void removeLast(ArrayList<String> strings) {
    strings.remove("Second");
    strings.remove("Third");
}

The sample output should look similar to the following:

[First, Second, Third]
[First]

What does the exercise mean by if the list is empty, the method does nothing?

I also keep getting error from local test saying the following:

removeLast method should remove the last element of the list.

Could someone help please?

CodePudding user response:

"If the list is empty, the method does nothing" --> Check if the list is empty or not, if empty just return nothing , else delete last element(as per your requirement)

Example:

public static void removeLast(ArrayList<String> strings) {
        
        if( (strings.isEmpty())) {
         return;
        } 
        else {
            strings.remove(strings.size()-1);
            
        }
        
    
    }

CodePudding user response:

you can first simply check list is empty of not if it is not empty than you can call size() methos it give last index number of list and simply you can call remove(int) method to remove last element.

 public static void removeLast(ArrayList<String> strings) {
   if(strings.isEmpty()){
   }
   else {
       strings.remove(strings.size()-1);
   }
  • Related