Bruce Orcullo Bruce Orcullo - 2 months ago 10
Java Question

Why do I get a "class expected" error while trying to get the length of an array?

Hi so I've been working on this code for a bit and I'm just down to one error that I can't solve. It keeps giving this upon compilation:

homework.java:19: error: class expected
for(int i = 0; i < spl[].length;i++;)
^


Here's my code

import java.io.*;

public class homework
{
public static void main (String args[]) throws IOException
{
String search, entry;
BufferedReader ent = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter filename: ");
search = ent.readLine();

BufferedReader in = new BufferedReader(new FileReader(search));
entry = in.readLine();
while(entry != null)
{
String spl[] = entry.split(",");
entry = in.readLine();
}
for(int i = 0; i < spl[].length;i++)
{
System.out.println(spl[i]);
}
}
}


Edit: So the problem was because it was an array. My problem now is how do I fix it because I have more errors now. What I was trying to do was split
String entry
into
array spl
then display all of its contents. Or is that not allowed? Sorry I'm still learning java.

Answer

You need to have nested loops, otherwise spl[] is not visible in the for-loop:

 while(entry != null)
 {
      String spl[] = entry.split(",");
      entry = in.readLine();
      for(int i = 0; i < spl.length;i++)
      {
          System.out.println(spl[i]);
      } 
}
Comments