java程序输入一段数字,判断0-9这10个数各有多少个怎么写?

2025-04-24 05:15:05
推荐回答(3个)
回答1:

想这类题用嵌套的for循环,然后再里层的for循环里做if判断就OK了
如果用switch 这个语句的话代码量是相当的大的;
public static void main(String[] args)
{
System.out.print("请输入:");
Scanner sc = new Scanner(System.in);
String num = sc.next();
String[] str = num.split();
for(int i = 0;i{
int a = str[i];
int tag = 0;
for(int j = 0;j{
if(a.equals(str[j]))
{
++tag;
}
System.out.println("有"+a+"这个数的个数:"+tag);
}
}
}

回答2:

public static void main(String[] args) {
// TODO Auto-generated method stub
String str = "123456";
String [] strs = str.split("");
int a =0; //如:a代表1出现次数
int b =0; //b代表2出现次数
//省略
for(int i = 0; i < strs.length; i++){
switch(Integer.parseInt(strs[i])){
case 1: a++;
case 2: b++;
//省略
}
}
for(int i = 0; i < strs.length; i++){
switch(Integer.parseInt(strs[i])){
case 1: System.out.print("1出现的次数为:"+a+"次");
case 2: b++;
//省略
}
}
}

回答3:

把你输入的一段数字看成字符串,然后可以考虑按位处理判断0-9,做计数就可以了!