xiaobaimengxino 2021-10-16 11:41 采纳率: 87.5%
浏览 42
已结题

输入若干个1到100的整数,求每个整数出现的次数,输入0,程序终止,我的代码哪错了,小白求指点


public static void main(String[] args){
        Scanner input=new Scanner(System.in);
        System.out.print("enter the integers between 1 and 100:");
        int a=input.nextInt();
        int [] shuzu=new int[100];
        for(int i=0;i<100;i++){
            shuzu[i]=i+1;
        }
        int [] shuzu2=new int[100];
        while(a!=0){
            for(int j=0;j<100;j++){
                if(shuzu[j]==a)
                    shuzu2[j]++;
                a= input.nextInt();
        }
            
    }
        for(int k=0;k<100;k++){
            if(shuzu2[k]!=0)
                System.out.print(shuzu[k]+"occours"+shuzu2[k]+"times" );
        }
}

输入整数没反应,输入0也无法终止程序

  • 写回答

2条回答 默认 最新

  • 字菁悠心 2021-10-16 12:03
    关注

    程序写的有问题呀,楼主!
    按照题干,我理解程序应该这样写:

    public static void main(String[] args){
            Scanner input=new Scanner(System.in);
            System.out.print("enter the integers between 1 and 100:");
            int a=-1;
            //用map集合存储每个数字出现的次数,其中key是数字,value是出现的次数
            Map<Integer,Integer> countMap=new HashMap<>();
            while(a!=0){
                a=input.nextInt();
                if(a<1 || a>100){
                    System.out.println("数字输入有误,请重新输入!");
                   continue;
                }
                Integer count = countMap.get(a);
                if(null==count){
                    count=1;
                }else{
                    count++;
                }
                countMap.put(a,count);
            }
            //遍历map集合,打印每个数字出现的次数
            for (Map.Entry<Integer, Integer> entry:countMap.entrySet()){
                Integer num = entry.getKey();
                Integer count = entry.getValue();
                System.out.println(num+"occours"+count+"times" );
            }
        }
    
    

    亲测有效!

    img

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 10月24日
  • 已采纳回答 10月16日
  • 创建了问题 10月16日