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

输入若干个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也无法终止程序

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

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

好像没有处理次数和退出