Wad*_*deG 0 java arrays hashmap
我如何使用 HashMap 来计算此数组中唯一条目的数量:
import java.util.Scanner;
public class Entry {
private Scanner scan = new Scanner(System.in);
public void userInput(){
Scanner scan = new Scanner(System.in);
System.out.println("Please tell me the amount of numbers you will be entering (Up to 50): ");
int [] arr = new int[scan.nextInt()];
for(int i=0;i<arr.length; i++) {
scan = new Scanner(System.in);
System.out.println("Please enter a number: ");
while(scan.hasNextInt()){
int x = scan.nextInt();
arr[i]= x;
break;
}
}
System.out.println(" ");
System.out.println("Results of Data Entry");
System.out.println("_____________________");
for(int i:arr){System.out.println(i + " occurs ");
}
}
}
Run Code Online (Sandbox Code Playgroud)
我想输出以显示输入的数字以及输入的次数。
所以如果我输入 1 5 6 6 7
它会显示
1 occurs 1
5 occurs 1
6 occurs 2
7 occurs 1
Run Code Online (Sandbox Code Playgroud)
List asList = Arrays.asList(array);
Set<String> mySet = new HashSet<String>(asList);
for(String s : mySet) {
System.out.println(s + " " + Collections.frequency(asList, s));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5206 次 |
| 最近记录: |