Java 为输入MMMGGKKCC生成类似-m3g2k3c2的输出

Java 为输入MMMGGKKCC生成类似-m3g2k3c2的输出,java,Java,基本上,我想展示一个字符在字符串中重复自身的次数,所以如果我有hheerrtt,我应该将其输出为h2e2r3t2,下面是我尝试的: import java.util.ArrayList; import java.util.List; public class HelloWorld{ static void process(String s){ int[] count = new int[10]; char[] array = s.toCharArray(); System.out.pri

基本上,我想展示一个字符在字符串中重复自身的次数,所以如果我有hheerrtt,我应该将其输出为h2e2r3t2,下面是我尝试的:

import java.util.ArrayList;
import java.util.List;

public class HelloWorld{
static void process(String s){

int[] count = new int[10];

char[] array = s.toCharArray();

System.out.println(s.length());

     int j=0;
     int m=0;
     int i=0;
     char c;
     ArrayList<Character> list = new ArrayList<Character>();
     for(j=0;j<s.length();j++){

         m=0;
         for(i=0;i<s.length();i++){

                 if(array[j]==array[i]){
                     m++;
                 }

            }
            System.out.println("char "+ array[j] + " is " + m);
            list.add(array[j]);
            //c=char(m);
            list.add(Character(m)); // gives an error, can't be donethis way

     }


 }
     public static void main(String []args){
        System.out.println("Hello World");
          process("hhhelloc");
     }
}
import java.util.ArrayList;
导入java.util.List;
公共类HelloWorld{
静态无效过程(字符串s){
int[]计数=新的int[10];
char[]数组=s.toCharArray();
System.out.println(s.length());
int j=0;
int m=0;
int i=0;
字符c;
ArrayList=新建ArrayList();

对于(j=0;j首先,假设m始终小于10。如果一个字符重复超过10次,该怎么办?将整数转换为字符并不能按您希望的方式工作

其次,您不需要两次传递数组,它可以在一个循环中完成。请检查以下代码:

public class HelloWorld
{
    private static void process( String s)
    {
        if( s == null || s.length() < 1)
            return;

        char[] array = s.toCharArray();
        StringBuilder builder = new StringBuilder();

        char lastChar = array[0];
        int count = 1;

        for( int i = 1; i < array.length; i++)
        {
            if( array[i] == lastChar)
                ++count;
            else
            {
                builder.append( lastChar);
                builder.append( count);

                lastChar = array[i];
                count = 1;
            }
        }

        if( count > 0)
        {
            builder.append( lastChar);
            builder.append( count);
        }

        System.out.println( builder.toString());
    }

    public static void main( String[] args)
    {
        System.out.println("Hello World");
        process("hhhelloc");
    }
}
公共类HelloWorld
{
私有静态无效进程(字符串s)
{
如果(s==null | | s.length()<1)
返回;
char[]数组=s.toCharArray();
StringBuilder=新的StringBuilder();
char lastChar=数组[0];
整数计数=1;
for(int i=1;i0)
{
builder.append(lastChar);
附加(计数);
}
System.out.println(builder.toString());
}
公共静态void main(字符串[]args)
{
System.out.println(“你好世界”);
过程(“HHELLOC”);
}
}

尝试添加
System.out.println(list);
在处理方法的末尾,该输出是什么?看起来您正在创建列表,但从未输出它,这解释了为什么您没有输出任何内容。无法像这样向arraylist添加整数-list.add(字符(m));也许你需要一个
列表
而不是
字符
s。也许是
字符串
?或者只是一个根本没有
列表
字符串。