Identifier Expected Error in Line 29

This is a program that has the user input a sentence then choose a character. It then tells the user how many times that character comes up but I am having trouble with one error since its expected an identifier. This is the code:

import java.util.Scanner;

public class StringTest{
public static void main(String[] args){
Scanner incomingString = new Scanner( System.in);
System.out.print("Type Something");
String s1 = incomingString.nextLine();
Scanner s2incomingString = new Scanner( System.in);
System.out.print("Choose a character"); 
String s2 = s2incomingString.nextLine();    

String result="";
StringBuilder sb = new StringBuilder(s1);
int counter = 0;
int start = 0;
int index = 0;

while (s1.length != -1){
 int counter = 0;
     index = s1.indexOf(s2,start);
     if (index != -1){
        counter++;
        start = index+1;
        }
     }    
 }
    System.out.println(index);         
}
Jon Skeet
people
quotationmark

This line is the immediate problem:

System.out.println(index);

It exists outside the body of any method, constructor or initializer - you can't do that. I suspect you meant it to be in the body of the main method.

This is much more obvious if you indent your code. Here's your code, indented appropriately (and skipping a bunch in the middle):

import java.util.Scanner;

public class Test{
    public static void main(String[] args){
        Scanner incomingString = new Scanner( System.in);
        ...
        int index = 0;

        while (s1.length != -1){
            int counter = 0;
            index = s1.indexOf(s2,start);
            if (index != -1){
                counter++;
                start = index+1;
            }
        }    
    }
    System.out.println(index);         
}

See how the System.out.println call is at the same level as you'd expect a method declaration? Always indent your code - most IDEs can do this for you as you type, or on demand. It makes things better for everyone.

Having fixed the problem by moving that statement inside the closing brace of the main method, you'll then see two more problems:

  • You're declaring counter twice, where the second declaration is in a place where the first declaration is already in scope.
  • You're using String.length as if it were a field, not a method; change s1.length to s1.length()

The code will then compile... it isn't clear what you're trying to do though, and String.length() will never return -1... Perhaps you wanted like while (index != -1)?

people

See more on this question at Stackoverflow