Hongxu Lin Hongxu Lin - 2 months ago 8
Java Question

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");
}
}

Answer

Your problem is here:

if(s.charAt(i)=s.charAt(i-1));

First of all, you must compare chars using == not =. Second, putting a ; right after the if statement will cause it to terminate immediately. In other words, the following line is no longer part of the if statement. Change to:

if(s.charAt(i) == s.charAt(i-1))

Edit

Regarding your comment, something like this should work, though I didn't test it. Just replace your current large if block with the below:

if (flag == '#' || flag == '$' || flag == '*' || flag == '&') {
    char last = ' ';
    char curr = ' ';
    int count = 1;
    for (int i = 0; i < s.length(); i++) {
        last = curr;
        curr = s.charAt(i);
        if (curr == last) {
            count++;
        }else {
            System.out.print(("" + count) + last);
            count = 1;
        }
    }
}
Comments