0

Deja vu code

Need help in below code - Deja vu code using java import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner word = new Scanner(System.in); String input = word.nextLine(); int l = input.length(); int n = 0; for(int i = 0;i < l;i++) { char temp = input.charAt(i); for(int j = 0; j < l;j++) { if(temp == input.charAt(j)) { n++; } if(n >= 2) { System.out.println("Deja vu"); break; } else { System.out.println("Unique"); break; } } break; } } } I am unable to get Deja vu as an output. Please help.

5th Oct 2022, 2:06 PM
Gouri
4 Respuestas
+ 1
break causes to loop exit. So check when break is executed then what us the output and n value. So rethink about logic. Your 2nd if-else should be out of inner loop. And in loop print only if you find duplicates and exit loop. After exiting loop, print Unique if loop don't print anything... You can start checking from next character j=i+1 instead of j=0 . Only break loop when you print Deja vu. Otherwise no need to break loop or print anything... Hope it helps to correct it..!
5th Oct 2022, 2:17 PM
Jayakrishna 🇮🇳
+ 1
Jayakrishna🇮🇳 the issue is, when I try to to set j as i + 1, it says array limit exceeded error.
6th Oct 2022, 8:42 AM
Gouri
+ 1
Yes. happens. You need to modify condition i<l-1; as well. (From i<l) . This is better way to your original logic. So first try to complete your own way then try this improvement. edit: it may need more changes. show the update code if it not worked...
6th Oct 2022, 11:47 AM
Jayakrishna 🇮🇳
+ 1
Jayakrishna🇮🇳 okay, will try again
6th Oct 2022, 3:50 PM
Gouri