编写程序,读取1~100之间的整数,然后计算每个数出现的次数。假定输入0表示结束。
注意:如果一个数出现的次数大于一次,则在输出是使用“times”。以升序显示数字。
package pack2;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeMap;
public class Count {
public static void main(String[] args) {
try(Scanner input = new Scanner(System.in);) {
count2(input);
}
}
/**计算数字的出现次数(方法一)*/
public static void count2(Scanner input) {
TreeMap<Integer, Integer> map = new TreeMap<>();
int integer;
System.out.print("Enter the integers between 1 and 100: ");
do {
integer = input.nextInt();
if(integer != 0)
if(!map.containsKey(integer))
map.put(integer, 1);
else
map.put(integer, map.get(integer) + 1);
}while(integer != 0);
Set<Entry<Integer, Integer>> set = map.entrySet();
for (Entry<Integer, Integer> entry : set) {
System.out.println(entry.getKey()+" occurs "+entry.getValue()+
(entry.getValue() == 1 ? " time" : " times"));
}
}
/**计算数字的出现次数(方法二)*/
public static void count1(Scanner input) {
int[] array = new int[100];
int integer;
System.out.print("Enter the integers between 1 and 100: ");
do {
integer = input.nextInt();
if(integer != 0)
array[integer - 1]++;
}while(integer != 0);
for (int i = 0; i < array.length; i++)
if(array[i] != 0)
System.out.println((i + 1)+" occurs "+array[i]+(array[i] == 1 ? " time"
: " times"));
}
}