4

I got a school assignment that I have to create a program that prints the first recurring character in a given string.

For example, if the input is "helloo", then it should output as "l". I wrote the following code but it prints "l" and "o" both.

String text = "helloo";
int length = text.length();
for (int i = 0; i <= length - 1; i++) {
 char curChar = text.charAt(i);
 for (int j = i + 1; j <= length - 1; j++) {
  if (curChar == text.charAt(j)) {
   System.out.println(curChar);
   break;
  }
 }
}

Can someone help me out with this? Thanks for any answers!

sanghvi
  • 43
  • 5

4 Answers4

3

You're breaking just the inner loop but not the outer loop. You can use break with a label for the outer loop. For example:

String text = "helloo";
int length = text.length();
outerloop:
for (int i = 0; i <= length - 1; i++) {
    char curChar = text.charAt(i);
    for (int j = i + 1; j <= length - 1; j++) {
        if (curChar == text.charAt(j)) {
            System.out.println(curChar);
            break outerloop;
        }
    }
}

Get more information here - How to break out of nested loops in Java?

Hope this helps, but you should try doing your school assignments yourself.

v_ag
  • 278
  • 1
  • 5
  • 17
0

I realize that you are asking for a direct fix to your current approach. But for those who might read this question in the future, there is a very sleek approach here using regular expressions:

String text = "helloo";
String match = text.replaceAll("^.*?(.)\\1.*", "$1");
System.out.println(match);

l

Demo

The basic idea of the pattern ^.*?(.)\1 is to consume the least number of characters in the string until we hit a single character which is followed by that same character.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

Here's another variant:

 String text = "helloo";
    ArrayList<String> a = new ArrayList<String>(Arrays.asList(text.split(Pattern.quote(""))));
    for(int i = 0; i < a.size()-1;i++) {
        if(a.get(i).compareTo(a.get(i+1)) == 0) {
            System.out.println(a.get(i));
            break;
    }
Cedric
  • 19
  • 6
0
        class FirstRepeatingChar
        {
        public static void main(String args[])
        {

         String s="hello";
          for(int i=0;i<s.length();i++)
          {
           for(int j=0;j<s.length();j++)
            { 
              if(s.charAt(i)==s.charAt(j))
                { 
System.out.println("  the First non repeating character is "  +s.charAt(i));
                 break;
                }
             }
           }
         }
         }
Tanay U
  • 1
  • 1
  • 3