vendredi 30 septembre 2016

how to check if the char in a string is the same as the previous char?

The problem asks to compare if the string has consecutive same letters and rewrite it as the number of the letter plus the letter, for example, AAAAA as in 5A. But when I use the if statement to make the comparison the output become some very long number instead of the desired result.

Here is a portion of the problem: Run-length encoding is a simple compression scheme best used when a dataset consists primarily of numerous, long runs of repeated characters. For example, AAAAAAAAAA is a run of 10 A’s. We could encode this run using a notation like *A10, where the * is a special flag character that indicates a run, A is the symbol in the run, and 10 is the length of the run.

Here is the code:

import java.util.Scanner;

public class RunLengthEncoding {

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.print("Enter input string: ");
    String s = input.nextLine();
    for (int a = 0; a < s.length(); a++) {
        if ((s.charAt(a) < 'A' || s.charAt(a) > 'Z')) {
            System.out.print("Bad input");
            System.exit(0);
        }
    }
    System.out.print("Enter flag character: ");
    char flag = input.nextLine().charAt(0);
    if (flag == '#' || flag == '$' || flag == '*' || flag == '&') {

        int count = 0;
        for (int i = 1; i < s.length(); i++) {
            if(s.charAt(i)=s.charAt(i-1));
            count++;

            if (count == 1)
                System.out.print(s.charAt(i));
            if (count == 2)
                System.out.print(s.charAt(i) + s.charAt(i));
            if (count == 3)
                System.out.print(s.charAt(i) + s.charAt(i) + s.charAt(i));
            else
                System.out.print(flag + s.charAt(i) + (count + 1));

        }

    } else
        System.out.print("Bad input");
}
}

Aucun commentaire:

Enregistrer un commentaire