public class ArrayList
{
// instance variables - replace the example below with your own
public void processinput (String s)
{
int[] a = {34, 25, 16, 98, 77, 101, 24};
ArrayList b = new ArrayList();
for(int i = 0; i < a.length; i++) {
int d = a[i];
if(d%2 > 0) {
b.add(new Integer(d));
}
}
for(int i = 0; i < b.size(); i++) {
System.out.print(b.get(i) + " ");
}
for(int i = a.length; i >= 0; i--) {
System.out.print(a[i] + " ");
}
}
}
3 Answers
Problem lies in naming your class as ArrayList. In your ArrayList class you do not have a method defined as add(). You are invoking your package ArrayList not java.util.ArrayList.
Change the declaration to java.util.List<Integer> b = new java.util.ArrayList<Integer>();. Also for clarity rename your class to something meaningful.
1 Comment
CoolBeans
Thanks for formatting Joachim. I wrote the answer from my iPad and unfortunately the formatting options do not show up on it.
I don't run code but at a glance I see that you start with a.length which will cause ArrayIndexOutOfBoundsException. fix this line like a.length - 1
for (int i = a.length - 1; i >= 0; i--) {
System.out.print(a[i] + " ");
}
and this line
ArrayList<Integer> b = new ArrayList<Integer>();
ArrayList<Integer>rather thanArrayList, since that way you get all the benefits of type-checking. You don't need to explicitly wrap up the integerdwithnew Integer(d); autoboxing will do this for you. Finally, the code in the last for loop will immediately cause an out of bounds exception, since indexa.lengthin arrayawill never succeed. You probably want to seti = a.length - 1.