I wrote the code as follows but it doesn't return the first recurring letter properly.
Example:
In the word "statistics" the recurring letters are s, t, and i. But the letter t recurs sooner than the letter s and i, but my program returns s instead of t.
What do I need to do for it to return t, using two for loops, as per the task in hand?
public class Main {
public static char FRL(String word){
for(int i = 0; i<word.length(); i++){
for(int j = i+1; j<word.length(); j++){
if(word.charAt(i) == word.charAt(j)){
return word.charAt(i);
}
}
}
return '0';
}
public static void main(String[] args) {
String word = "statistics";
if (FRL(word) != '0'){
System.out.println(FRL(word));
}else{
System.out.println("No reccurring letter!");
}
}
}
You can reduce eliminate the nested loop and improve the performance by storing every encountered character in a
HashSet:But if you have a requirement to use a nested loop, then you should fix the initialization expression and condition of the inner
forloop, i.e. we should be check characters starting from index0inclusive and up to indexiexclusive:By the way,
getFirstRecuringLetter()would be a better method name thanFRL.