Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/369.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java压缩不返回?_Java_String - Fatal编程技术网

Java压缩不返回?

Java压缩不返回?,java,string,Java,String,我的代码应该做的是转换输入字符串并输出压缩版本 例如输入:“QWWW”输出:“3q3w” 但是我的代码什么也不返回 PSIO只是一个输入系统 public class Compress { public static String compress(String original){ String s = ""; char s1 = original.charAt(0); int count = 1; for(int i

我的代码应该做的是转换输入字符串并输出压缩版本

例如输入:“QWWW”输出:“3q3w”

但是我的代码什么也不返回

PSIO只是一个输入系统

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


    }

}
公共类压缩{
公共静态字符串压缩(字符串原始){
字符串s=“”;
字符s1=原始字符(0);
整数计数=1;
对于(int i=0;i
您的罐应该是这样的:

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;
}
String returnString=”“;
对于(int index=0;index

在这里,我们循环考虑字符串(外部为循环),并检查相邻值是否与我们不断添加的值相同。(内部while循环)

您应该使用调试器逐步完成代码。或者通过handWell,我看到“QWWW”的输入打印“4q”的输出…当我运行代码时,我得到了“4q”。你在计算元素0两次,退出循环后不考虑活动跨距。Cyrstal ball说:无论IO是什么,它都不像你认为的那样工作。代码有点不正确。如果我键入“QWWweeerTyyyyyQQQQweerTTT”,结果是2q9w5e2r6y4q3E3T,它不会显示一个t或一个r。编辑您需要做的只是在第五行添加+1谢谢朋友!它对我来说很好1q9w5e2r1t5y4q1w2E1r3T确保你没有引入一些副作用。我发现你的for循环中没有索引+,这是故意的吗?是的!它处于内部循环的while状态。