Issue
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?
Solution
"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);
}
}
Answered By - user19856836
Answer Checked By - Robin (JavaFixing Admin)