Cannot find symbol: method add
Why am I receiving the following error: cannot find symbol: method add
? This is my code:
import java.util.*
public class ArrayList {
// instance variables - replace the exa开发者_如何学Cmple 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 - 1; i >= 0; i--) {
System.out.print(a[i] + " ");
}
}
}
How can I resolve this error?
Reading your question again, I assume you are missing
import java.util.*;
at the start of your class. This is the only way you could be getting this error. BTW you should also be getting an error like "Cannot resolve symbol ArrayList" which tells you what the problem is.
Change the last loop to be
for(int i = a.length-1; i >= 0; i--) {
With experience you will be able to read error messages and understand what they mean. In this case
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
at Main.main(Main.java:33)
On line 33, (or what ever it is in your code) you tried to accessed an index which is beyond the end of the array. The last element of array a
is a.length-1
because the first element is 0
It is important to read error message carefully because they are often the best clue as to what the problem is and how to fix it.
When you post a question you should post the error you are getting.
There is ArrayIndexOutOfBoundsException: 7 . fix this line
for(int i = a.length-1; i >= 0; i--)
Your class is called ArrayList
, and this is hiding java.util.ArrayList
, hence your compilation errors. Either change the name of your class, or use the full name of java.util.ArrayList
when declaring b
.
精彩评论