Click here to Skip to main content
15,940,430 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am getting same char output multiple times JAVA

input - Shubham
output - hh

I want my output -
only - h

Here is my code -

What I have tried:

Scanner sc = new Scanner(System.in);
System.out.println("Enter the string ??");
String str = sc.nextLine();
str=str.toLowerCase();
char[] st = str.toCharArray();
System.out.println(Arrays.toString(st));
int count = 0;
for(int i=0;i<str.length();i++) {
    for(int j=i+1;i<str.length();i++) {
        if(st[i]==st[j]) {
            count+=1;
            }
        if(count>0) {
            System.out.print(st[i]);
            count=0;
            }
        }
    }
Posted
Updated 1-Apr-23 23:25pm

1 solution

Consider using else if instead of if:

I'd simplify that code:
Create an array of 26 integers, preset it to all zeros - call it letterCounts
Loop through your input string once, for each character, if it's between 'a' and 'z' inclusive, increment the appropriate element of letterCounts

After the loop, add a second loop which checks letterCounts - all values which are two or more indicate duplicates so print the appropriate letter.

This means you aren't looping through potentially long strings N2 times which is what your code is doing, as well as getting rid of your problem. Instead, you make N passes through your loop, plus 26 through the counts.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900