In: Computer Science
Could I please get explainations and working out as to how to get to the answers.
Note that is where part of the answer goes.
1.
Consider the following ArrayList list:
ArrayList list = new ArrayList(Arrays.asList(10,70,20,90));
//list = [10, 70, 20, 90]
Complete the following statements so that list contains the items [50, 70, 20]
Do NOT include spaces in your answers.
list.remove( ); list. ( , 50);
2.
Assume there exists an ArrayList list that contains the items
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100, ....]
(So, we know the first item is 10, second item is 20, but we don't know how many items it contains. You may assume it contains at least 10 items)
Complete the following code that displays every other item starting at the fifth item (so, the pattern 50 70 90 ...)
Do NOT include spaces in your answer.
for(int i= ; i < ; ) {
System.out.println( +" ");
}
3.
Complete the following function that returns the number of negative (less than 0) items in ArrayList list.
public static int countNegatives(ArrayList list) {
int result = ;
for(int i=0; i < list.size(); i++) {
if( ) { ; }
} return result; }
Ques 1)
There will be two remove statements to remove elements 10 and 90.
remove function takes the index of the element to remove. So the first remove statement will be as list.remove(0) to remove first element because list indexing starts from 0 and the second remove statement will be list.remove(list.size()-1) because list.size() returns the last index of element + 1.
The third statement to add 50 to list will be list.add(0, 50). This will add 50 as the first element in the list.
I'll add sample code for all question for your reference.
Sample Code:-
list.remove(0);
list.remove(list.size()-1);
list.add(0,50);
Ques 2)
To get the element of list from 5 element to every other element, a for loop has to be implemented iterating from the 5 element and incrementing the loop variable by 2 for every iteration.
5th element of array will have index as 4 since array indexing starts from 0.
So loop variable will start from 4 and will be incremented by 2 in every iteration. Hence the variable values will be as 4, 6, 8, 10 and so on.
Sample Code:-
for(int i=4;i<list.size();i+=2)
{
System.out.println(list.get(i)+"");
}
Ques 3:-
Initialize the value of result as 0, since in the starting of function there are no negative values, unless we check whole array.
To count the number of negatives in the list we have to iterate over complete list and check if the value at that index of list in less than 0.
If the value is less than 0, then increment the count of result value.
Sample Code:-
public static int countNegatives(ArrayList<Integer> list){
int result = 0;
for(int i=0;i<list.size();i++)
{
if(list.get(i)<0){
result++;
}
}
return result;
}
Note:- Please comment down if you face any problem. :)