I need help with this one piece of java code. I need this code to run and succes
ID: 3903545 • Letter: I
Question
I need help with this one piece of java code. I need this code to run and successfully add items into the collection. So I need to modify line 10 to be whatever. Just adding them to the array. Here is my code so far. This is the only part I havent solved of the overall assignment
interface ICompMeth {
int comp(int pos, int value);
}
class Collection {
private int[] nums;
public Collection(int ... list) {
// TODO: Implement this method
nums.add(int ... list); //here
}
public int size() {
// TODO: Implement this method
return nums.length;
}
public int get(int index) {
// TODO: Implement this method
return nums[index];
}
public void printAll() {
System.out.print("Numbers: ");
for (int n : nums) {
System.out.print(n + " ");
}
System.out.println();
}
}
public class Sample {
public static void main(String[] args) {
Collection nums = new Collection(1, 3, 4, 5, 8, 10, 12);
nums.printAll();
//ICompMeth meth = /* TODO: utilize the functional interface ICompMeth */;
Collection targets = new Collection(3, 8, 13, 5, 0);
// TODO:
// run through targets
// search for each one using binSearch below
// print either "value found" or "value not found" with "value" replaced with the target int
}
private static int binSearch(Collection c, int target, ICompMeth meth) {
// TODO: Implement this method
}
}
Explanation / Answer
Please check the modified code below for adding the elements:
interface ICompMeth {
int comp(int pos, int value);
}
class Collection {
private int[] nums;
public Collection(int ... list) {
// TODO: Implement this method
//nums.add(int ... list); //here
nums=new int[list.length];
for(int i=0;i<list.length;i++)
{
nums[i]=list[i];
}
}
public int size() {
// TODO: Implement this method
return nums.length;
}
public int get(int index) {
// TODO: Implement this method
return nums[index];
}
public void printAll() {
System.out.print("Numbers: ");
for (int n : nums) {
System.out.print(n + " ");
}
System.out.println();
}
}