用Java编写一个程序对用户输入的任意一组字符如{3,1,4,7,2,1,1,2,2}输出其中出现次数最多的字符

对用户输入的任意一组字符如{3,1,4,7,2,1,1,2,2}输出其中出现次数最多的字符,并显示其出现次数。如果有多个字符出现次数均为最大且相等,则输出最先出现的那个字符和它出现的次数。例如,上面输入的字符集合中,“1”和“2”都出现了3次,均为最大出现次数,因为“1”先出现,则输出字符“1”和它出现的次数3次。
要求:使用分支、循环结构语句实现。

import java.util.HashMap;
import java.util.Scanner;

public class A {
  public static void main(String argvs[]) {
      String line;
      Scanner sc = new Scanner(System.in);

      while(sc.hasNextLine()) {
          line = sc.nextLine();
          if (line.length()==0) break;

          String []s = line.split(",");
          int a[] = {0,0,0,0,0,0,0,0,0,0};

          for (String i: s) {
              a[Integer.valueOf(i)] ++;
          }
          int p = 0, max = a[0];
          for (int i=1;i<10;i++) {
              if (max<a[i]) {
                  p = i;
                  max = a[i];
              }
          }
          System.out.printf("出现次数最多的字符是:%c, 次数是%d\n", 0x30 + p, max);
      }

      sc.close();
  }
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2019-01-11

实现的方法有很多,以下是一次遍历就能实现的方法

    public static void main(String[] args) {
//        以什么格式输入就用什么方法解析数据
//        String line;
//        Scanner sc = new Scanner(System.in);
//        line = sc.nextLine();
//        String[] split = line.split(",");
        Integer[] array = {15,1,2,5,1,3,5,4,12,15};//要操作的数组
        System.out.println(  getMostInteger( array ) );
//        sc.close();
    }

    public static String getMostInteger( Integer[] arrayMath ){
        //key保存出现过的数字,value保存形式为 下标_出现次数长度的字符。
        Map<Integer , String> m = new HashMap<>();
        int max = 1;//保存最大出现的次数
        int minIndex = 0;//保存最大数的下标
        for( int i = 0 ; i < arrayMath.length ; i ++ ){
            if( m.containsKey( arrayMath[i] ) ){
                m.put( arrayMath[i] , m.get( arrayMath[i] ) + 1 );
                String[] s = m.get(arrayMath[i]).split("_");//将索引和出现次数分离
                int length = s[1].length();//获取出现次数
                if( length > max ){
                    max = length;
                    minIndex = Integer.parseInt( s[0] );
                }else if( length == max ){
                    if( Integer.parseInt( s[0] ) < minIndex ){
                        minIndex = Integer.parseInt( s[0] );
                    }
                }
            }else {
                m.put( arrayMath[i] , i + "_" + 1 );
            }
        }
        String result = "出现次数最多的是" + arrayMath[minIndex] + "出现的次数为" + max;
        return result;
    }

第2个回答  2019-01-10
用一个map存,key 存字符 ,遍历这组字符,key不存在就存(key,0),如果key已经存在了就value++ ,遍历完了,之后就看那个value大就行,至于取什么就简单了。追问

麻烦写个程序

相似回答