简体   繁体   中英

Java Compress no return?

what my code is supposed to be doing is converting input strings and outputing the compressed versions

Ex. Input: "qqqwww" Output: "3q3w".

But my code returns nothing.

PS IO is just an input system.

public class Compress {
    public static String compress(String original){
        String s = "";

        char s1 = original.charAt(0);
        int count = 1;

        for(int i = 0; i < original.length(); i++){
            char c = original.charAt(i);

            if(c == s1){
                count++;
            }
            else{
                s = s + count + s1; //i think the problem is here right???
                count = 1;
            }
            s1 = c;
        }
        return s;

    }

    public static void main(String[] args){
        String s = IO.readString();

        String y = compress(s); 

        System.out.println(y);


    }

}

Your could should look like this :

String returnString="";
    for (int index = 0; index < original.length();) {
        char currentChar = original.charAt(index);
        int counter=1;
        while(++index < original.length() && currentChar==original.charAt(index)) {
            counter++;
        }
        returnString=returnString+counter+currentChar;
    }
    return returnString;
}

Here we loop thought the string (outer for loop) and check if the adjacent values are same the we keep adding them. (inner while loop)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM