【发布时间】:2021-07-16 22:22:12
【问题描述】:
我需要编写一个循环来查看 HashMap 中的值是否相等,以及它们是否出现了多少次。将通过 Scanner 输入一组数字(示例输入如下) 下面的代码会将 count 的键和 HashSet 的值放入 hashMap 中。
public static void main(String[] args) {
System.out.println("Type in your numbers followed by spaces and press enter");
System.out.println("After every set entered type in any letter to enter more sets");
System.out.println("Or enter * to finish");
HashMap<Integer, HashSet<Integer>> hset = new HashMap<>();
Scanner sc = new Scanner(System.in);
int count = 1;
HashSet<Integer> list = new HashSet<>();
while(sc.hasNextLine()) {
while(sc.hasNextInt()) {
list.add(sc.nextInt());
}
hset.put(count, new HashSet<>(list));
count++;
list.clear();
sc.nextLine();
if(sc.nextLine().equals("*")) {
System.out.println("working");
break;
}
}
for(int i=0; i<count; i++){
//some code goes here
//if(hset.get(x) == hset.get(j)) or something along these lines
}
}
//Sample Scanner input
1 2 3 4 5
10 9 8 7
5 4 3 2 1
1 1 1 1 1
1 2 3 5
1 2 3 6
6 4 2
2 4 6
4 2 6
4 6 2
6 2 4
1 3 2 4 5
15 14 13
5 3 2 1
79
7 9
//What I need the output to look like
[7, 9]=1
[1]=1
[7, 8, 9, 10]=1
[13, 14, 15]=1
[1, 2, 3, 5]=2
[1, 2, 3, 6]=1
[2, 4, 6]=5
[1, 2, 3, 4, 5]=3
[79]=1
【问题讨论】:
-
您是否检查过您的代码在 for 循环之前是否正常工作?因为不应该。您当前正在将整个输入读入一个 HasSet(即只有一个 HashMap 条目)