illegal start of expression error!!!!
Hey...this is my code to reverse each word of the string input!!
At line 12 it says 'illegal start of expression'....any idea how to troubleshoot this ??
Code Java:
//Reverse each word of the sentence
import java.io.*;
class rev_word
{
public static void main (String args[ ])throws IOException
{
BufferedReader br = new BufferedReader (new InputStreamReader (System.in));
String S = br.readLine();
S=S+"";int k=0; String word="";
for (int i=0; i<S.length();i++)
{
if (S.charAt(i) == ' ')) // <-- error shown at this line 'illegal start of expression'
{
word=S.substring (k, i);
k= i+1;
for (int j=word.length();j>=0;j++)
System.out.print (word.charAt(j));
System.out.print (" ");
}
}
}
}
Re: illegal start of expression error!!!!
Check the number of parenthesis: see Common java mistakes
Re: illegal start of expression error!!!!
Extra bracket in if condition. It should be:
if(S.charAt(i)==' ')
Re: illegal start of expression error!!!!
ok i removed the extra paranthesis
and now the code luks somewhat like
Code Java:
//Reverse each word of the sentence
import java.io.*;
class rev_word
{
public static void main (String args[ ])throws IOException
{
BufferedReader br = new BufferedReader (new InputStreamReader (System.in));
System.out.println("Enter a String");
String S = br.readLine();
S=S+"";int k=0; String word="";
for (int i=0; i<S.length();i++)
{
if (S.charAt(i) == ' ')
{
word=S.substring (k, i);
k= i+1;
for (int j=word.length();j>=0;j++)
System.out.print (word.charAt(j));
System.out.print (" ");
}
}
}
}
it has compiled but now its giving a runtime error as follows:
"Enter a String
I love playing guitar
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1
at java.lang.String.charAt(String.java:686)
at rev_word.main(abc.java:18)"
Re: illegal start of expression error!!!!
I believe this issue is caused by problems here:
Code Java:
for (int j = word.length(); j >= 0; j++)
System.out.print(word.charAt(j));