I've got a problem with my Java program. There is an error in my code on line 16 (t = T[i];) which implies an error on line 12. It says :
Syntax error on token "=",VariableInitializer expected after this token.
Could I have some help ?
public class Ngrams {
public static boolean estPrefixe(String t, String s) {
int Longs = s.length();
if (t.substring(0, Longs) == s) {
return true;
} else {
return false;
}
}
public static int nbOccurences(String[] T, String s) {
int compteur = 0;
String t = null;
for (int i = 0; i < T.length; i++) {
t = T[i];
if (estPrefixe(t, s)) {
compteur++;
}
return compteur;
}
}
3 Answers 3
Notwithstanding the fact that you're comparing Strings with == instead of .equals(), and that a right bracket seems to have gone AWOL, at the end of your program, you're "missing" a return statement in nbOccurences. Even though you have one in the for-loop, if you never enter the loop, you don't return anything.
Move your return statement down one line, outside of the loop instead.
public static int nbOccurences(String[] T, String s) {
int compteur = 0;
String t = null;
for (int i = 0; i < T.length; i++) {
t = T[i];
if (estPrefixe(t, s)) {
compteur++;
}
}
return compteur;
}
Comments
The method nbOccurences does not always return an int value. If T is null or empty (length = 0) no value is returned. So you should add another return statement after the for loop.
As others mentioned already you should use equals to compare strings. This however, is not producing a syntax error.
Comments
Well there's a serious bug in this line:
if (t.substring(0, Longs) == s) {
This test will always be false, because == compares object references, not values. Change it to:
if (t.substring(0, Longs).equals(s)) {
But the whole method is pointless. Change it to:
public static boolean estPrefixe(String t, String s) {
return t.startsWith(s);
}
Or just delete the method altogether because it adds no value whatsoever.
1 Comment
t and s are the same object than result of this equation will be true. In the same time, yes, topic starter should always use .equals instead of =.
==, use proper caseString.startsWith}missing. I may have accedently fixed the code when trying to fix the formatting.