0

what's wrong in this code

You aren't paying attention and you accidentally type a bunch of random letters on your keyboard. You want to know if you ever typed the same letter twice, or if they are all unique letters. Task: If you are given a string of random letters, your task is to evaluate whether any letter is repeated in the string or if you only hit unique keys while you typing. Input Format: A string of random letter characters (no numbers or other buttons were pressed). Output Format: A string that says 'Deja Vu' if any letter is repeated in the input string, or a string that says 'Unique' if there are no repeats. Sample Input: aaaaaaaghhhhjkll Sample Output: Deja Vu

19th May 2021, 4:33 AM
Bot
Bot - avatar
4 Answers
+ 2
Modify 2nd for loop to j<s.length().. It's done!!
19th May 2021, 4:41 AM
sarada lakshmi
sarada lakshmi - avatar
+ 2
import java.util.Scanner; class test { int i, j; boolean flag=true; public void check(){ Scanner sc=new Scanner(System.in); String s=sc.nextLine(); for(i=0;i<s.length()-1;i++) { for(j=i+1;j<s.length();j++) { if(s.charAt(i) ==s.charAt(j)) { flag=false; break; } } } if(flag==true) System.out.println ("Unique") ; else System.out.println ("Deja Vu") ; } }; public class Program { public static void main(String[] args) { test t=new test(); t. check(); } }
19th May 2021, 5:01 AM
Atul [Inactive]
+ 2
This should be done
19th May 2021, 5:01 AM
Atul [Inactive]
+ 1
❤️💻Programmer💻❤️ As index start from 0 so if you do <= then it will go beyond the index and you get indexOutOfBound exception. So either you do (j < s.length) or do ( j <= s.length - 1) import java.util.Scanner; class Test { public boolean check(String s) { int i, j; boolean flag = true; for (i = 0; i < s.length(); i++) { for (j = i + 1; j < s.length(); j++) { if (s.charAt(i) == s.charAt(j)) { flag = false; break; } } } return flag; } } public class Program { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.nextLine(); Test t = new Test(); boolean flag = t.check(s); System.out.print(flag ? "Unique" : "Deja Vu"); } }
19th May 2021, 5:10 AM
A͢J
A͢J - avatar