计算数字出现次数java_java – 使用数组计算每个数字的出现次数

我需要使用数组编写一个程序,它接受一个数字并返回该数字中每个数字的事件数.我想我可能在这里过于复杂.

import java.util.*;

class Exercice7 {

public static void main(String [] args) {

Scanner sc = new Scanner(System.in);

System.out.println("Veuillez saisir un nombre naturel:"); // Get number

int n = sc.nextInt(); // Store number as n

String str = Integer.toString(n); // Store n as string

int length = str.length(); // Store string length as length

int arr[] = new int[length]; // Declare array with as many elements as n has digits

int digit[] = {0,1,2,3,4,5,6,7,8,9}; // Declare array with the digits to look for

int count = 0; // Number of occurences of each digit

for (int i=(length-1); i>=0; i--) { // Fill array with digits from number input

while (n>0) {

arr[i]= n%10;

n = n/10;

}

}

for (int j=0; j<10; j++) {

count = 0;

for (int i=0; i

if (arr[i]==digit[j]) {

count++;

}

}

if (count>0) {

System.out.println(digit[j] + " occurs " + count + " times.");

}

}

}

}

这段代码只返回0和1的数字,无论如何都是错的.有人能把我推向正确的方向吗?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值