You have referred arrayStr[i] instead of arraylistStr[i]. So, compiler is saying spelling mistake.
Second thing before using collections/array/anything, first go through the usage, its syntax.
1. You cannot refer ArrayList's element as arraylistStr[i]. You must use get() to retrieve its element.
2. For checking the size of ArrayList, arraylistStr.size() is used not arraylistStr[i].length()
Originally Posted by
mwardjava92
// I was asked to create an arraylist of strings, print out each element in
// the arraylist, the longest string and it's location. Below are the errors I am getting and the code.
Errors :
ArrayListString.java:27: cannot find symbol
symbol : variable length
location: class java.util.ArrayList<java.lang.String>
for(int i = 0; i < arraylistStr.length; i++)
^
ArrayListString.java:29: cannot find symbol
symbol : variable arrayStr
location: class ArrayListString
if(arrayStr[i] != null) //int index = 0;
^
ArrayListString.java:31: array required, but java.util.ArrayList<java.lang.String> found
if(arraylistStr[i].length() > largest)
^
ArrayListString.java:33: array required, but java.util.ArrayList<java.lang.String> found
largest = arraylistStr[i].length();
^
ArrayListString.java:39: array required, but java.util.ArrayList<java.lang.String> found
System.out.println("Element " + location + ", " + arraylistStr[largest]
^
5 errors
import java.util.ArrayList;
public class ArrayListString
{
public static void main(String args[])
{
ArrayList<String> arraylistStr = new ArrayList<String>();
arraylistStr.add("Jim Bob"); // Add Strings to the first 3 elements
arraylistStr.add("Bobby Jones");
arraylistStr.add("Rob Styles");
for(int count = 0; count <= arraylistStr.size(); count++) // Print each element in arraylist
{
System.out.println(arraylistStr.get(count));
}
int largest = 0, location = 0; // Start largest off at 0
for(int i = 0; i < arraylistStr.length; i++)
{
if(arrayStr[i] != null) //int index = 0;
{
if(arraylistStr[i].length() > largest)
{
largest = arraylistStr[i].length();
location = i;
}
}
}
System.out.println("Element " + location + ", " + arraylistStr[largest]
+ ", is the largest and its size is " + largest);
}
}