How to make sure the Print statement is executed only when the characters are distinct?

codexhammer 138 :

So, I'm writing a program for String compression. if the input is aabbccc, the output should be a2b2c3.

But in my program, my output is a2a2b2b2c3c3c3. That is because my Print statement is in a for loop. Which isn't supposed to be there.

How can I execute the print statement only when two characters in the String are not equal? so that I get the right output?

I've tried other ways of doing the String Compression program, but this way using Collections seems the easiest to me.

public class Compress {

   static int i;
   static int freq;

public static void main(String args[]) {
  System.out.println("Enter a String");
  Scanner sc= new Scanner(System.in);
  String  str=sc.nextLine();
   List<Character> arrlist = new ArrayList<Character>();
   for(int i=0; i<str.length();i++){
       arrlist.add(str.charAt(i));
   }
   for(int i=0; i<str.length();i++){
       freq = Collections.frequency(arrlist, str.charAt(i));
           System.out.print(str.charAt(i)+""+freq);
   }
 }
}

Desired result

Input: aabbccc
Output: a2b2c3

What I'm getting

Input: aabbccc
Output: a2a2b2b2c3c3c3
Allan :

You can use the following code, there is no need to have 2 nested loops to do the compression. One loop passing through the input string is more than enough.

class Compress {

  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.print("Enter a string: ");
    String inputString = scanner.nextLine();
    scanner.close();
    System.out.println("Compressed Input: " + compressInput(inputString));
  }

  private static String compressInput(String str) {
    if(str.isEmpty())
        return "";
    if(str.length() == 1)
        return str + "1";

    StringBuilder result = new StringBuilder();
    int cmpt = 1;
    for (int i = 1; i < str.length(); i++) {
      if(str.charAt(i - 1) == str.charAt(i))
          cmpt++;
      else {
          result.append(str.charAt(i-1));
          result.append(cmpt);
          cmpt=1;
      }
    } 
    result.append(str.charAt(str.length()-1));
    result.append(cmpt);
    return result.toString();
  }

}

Example of output:

Enter a string: aaabbbbccddddeeeefg
Compressed Input: a3b4c2d4e4f1g1

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=135788&siteId=1