使用Java 从键盘输入10个整数,合法值为1,2,3 其他为非法数字,试编程统计1,2,3的个数和非法数字个数

2024-11-09 09:41:44
推荐回答(2个)
回答(1):

Java Code

import java.util.Scanner;
class NumCounter
{
public static void main(String[] args)
{
System.out.println("Input 10 numbers:");
Scanner sc=new Scanner(System.in);//receive data from console
int[] num=new int[10];
int[] count=new int[4];
for(int i=0;i<10;i++)
{
num[i]=sc.nextInt();//get data
switch(num[i])
{
case 1:
count[0]++;
break;
case 2:
count[1]++;
break;
case 3:
count[2]++;
break;
default:
count[3]++;

}
}
System.out.print("Your Input:");
for(int i=0;i<10;i++)
System.out.print(num[i]+" ");
System.out.print("\n");
System.out.println("You get: "+count[0]+" Number \"1\", "+
count[1]+" Number \"2\", "+count[2]+" Number \"3\" and "+count[3]+" Others");
}
}

Debug:

回答(2):

package Demo;
import java.util.Scanner;
public class Demo {
public static void main(String[] args) {
int[]nums=new int[10];
int[] count=new int[4];
System.out.println("请输入十个数");
Scanner input=new Scanner(System.in);
for(int i=0;iSystem.out.print("输入的第"+(i+1)+"个数为:");
nums[i]=input.nextInt();
}
System.out.print("输入的十个数为:");
for(int i=0;iSystem.out.print(nums[i]+" ");
switch(nums[i]){
case 1:
count[0]+=1;
break;
case 2:
count[1]+=1;
break;
case 3:
count[2]+=1;
break;
default:
count[3]+=1;
break;
}
}
System.out.println("\n数字1的个数:"+count[0]);
System.out.println("数字2的个数:"+count[1]);
System.out.println("数字3的个数:"+count[2]);
System.out.println("非法数字的个数:"+count[3]);

}
}
(绝对正确,大家可以粘贴到自己的eclipse里面验证)