Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

232
Vistas
Duplicate output in Java

I'm new here and still learning. Today I learn find duplicate in string. From https://www.javatpoint.com/program-to-find-the-duplicate-characters-in-a-string, I try to learn complete code from web.

When string = "Great responsibility" the output will be:

 Duplicate characters in a given string: 
r
e
t
s
i

because it has duplicate character r e t s i

And when string is "great" the output is

 Duplicate characters in a given string: 

The output is blank because there are no duplicate characters, so I give a description "no duplicate" to define no character duplicate and the output goes like this

Duplicate characters in a given string: 
no duplicates
no duplicates
no duplicates
no duplicates
no duplicates

This returns too many descriptions.

My code

public class DuplicateCharacters {  
    public static void main(String[] args) {  
        String string1 = "Great";  
        int count;  
          
        //Converts given string into character array  
        char string[] = string1.toCharArray();  
          
        System.out.println("Duplicate characters in a given string: ");  
        //Counts each character present in the string  
        for(int i = 0; i <string.length; i++) {  
            count = 1;  
            for(int j = i+1; j <string.length; j++) {  
                if(string[i] == string[j] && string[i] != ' ') {  
                    count++;  
                    //Set string[j] to 0 to avoid printing visited character  
                    string[j] = '0';  
                }  
            }  
            //A character is considered as duplicate if count is greater than 1  
            if(count > 1 && string[i] != '0')  
                System.out.println(string[i]);  
            else 
             System.out.println("no duplicates"); 
        }  
    }  
} 

How can I print only one description without repetition? I tried return 0; but it does not work.

Expected output

Duplicate characters in a given string: 
no duplicates
over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

Separate the logic for finding duplicates from how you report the findings to the user. Move the logic for finding the duplicates into a method. Pass the results of that output to another method. The main method invokes the first and passes the output to the second.

public static void main(String[] args) {
  String s = .... whatever you are searching for duplicates in ....
  reportDuplicates(findDuplicates(s)):
}
public static List<Character> findDuplicates(String s) {
  ... returns a List containing duplicates ...
}
public static void reportDuplicates(List<Character> duplicates) {
  if (null == duplicates || duplicates.isEmpty()) {
    ... report no duplicates ...
  } else {
    ... output the duplicates
  }
}
over 4 years ago · Santiago Trujillo Denunciar

0

Add a flag to your program that indicates whether there are duplicates or not. And after loop check whether this flag is true or false.

This method would look like below. I commented code where I updated it.

public static void main(String[] args) {
    String string1 = "Great";
    int count;

    //Converts given string into character array
    char string[] = string1.toCharArray();

    // here is flag added
    boolean noDuplicates = true;

    System.out.println("Duplicate characters in a given string: ");
    //Counts each character present in the string
    for(int i = 0; i <string.length; i++) {
      count = 1;
      for(int j = i+1; j <string.length; j++) {
        if(string[i] == string[j] && string[i] != ' ') {
          count++;
          //Set string[j] to 0 to avoid printing visited character
          string[j] = '0';
        }
      }
      //A character is considered as duplicate if count is greater than 1
      if(count > 1 && string[i] != '0') {
        System.out.println(string[i]);

        //here is flag updated if duplicates are found
        noDuplicates = false;
      }
    }

    //here is flag check
    if (noDuplicates) {
      System.out.println("no duplicates");
    }
  }

And btw. Your algorithm has O(n^2) time complexity. You can figure out one that is better ;-)

over 4 years ago · Santiago Trujillo Denunciar

0

It's normal your System.out.println("no duplicates"); is in your loop so each time a character is not duplicate you print "no duplicates".

You can defined a boolean that will become true if one duplicate it's found, like this :

public class DuplicateCharacters {
public static void main(String[] args) {
    String string1 = "Great";
    int count;

    //Converts given string into character array
    char string[] = string1.toCharArray();

    System.out.println("Duplicate characters in a given string: ");
    //Counts each character present in the string
    Boolean dupCarac = false;
    for(int i = 0; i <string.length; i++) {
        count = 1;
        for(int j = i+1; j <string.length; j++) {
            if(string[i] == string[j] && string[i] != ' ') {
                count++;
                //Set string[j] to 0 to avoid printing visited character
                string[j] = '0';
            }
        }
        //A character is considered as duplicate if count is greater than 1
        if(count > 1 && string[i] != '0'){
            System.out.println(string[i]);
            dupCarac = true;
        }
    }
    if (!dupCarac){
        System.out.println("no duplicates");
    }
}

PS: Please put {} on your if and else.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda