Java 在循环中的不同行上从扫描仪读取多个哈希集

Java 在循环中的不同行上从扫描仪读取多个哈希集,java,hash,hashmap,hashset,Java,Hash,Hashmap,Hashset,我将让用户使用扫描仪并键入许多不同的哈希集(下面是示例输入),我需要将所有这些转换为不同的哈希集,然后保存到哈希映射中。我的代码将把输入的数字放入一个哈希集中,但它不能告诉下一个哈希集是什么时候,也就是说,它不能告诉下一个行集是什么时候出现的 public static void main(String[] args) { HashMap<Integer, HashSet<Integer>> hset = new HashMap<>(); Sc

我将让用户使用扫描仪并键入许多不同的哈希集(下面是示例输入),我需要将所有这些转换为不同的哈希集,然后保存到哈希映射中。我的代码将把输入的数字放入一个哈希集中,但它不能告诉下一个哈希集是什么时候,也就是说,它不能告诉下一个行集是什么时候出现的

public static void main(String[] args) {
    HashMap<Integer, HashSet<Integer>> hset = new HashMap<>();
    Scanner sc = new Scanner(System.in);
    int count = 1;
    HashSet<Integer> list = new HashSet<Integer>();

    System.out.println("Enter numbers");
    while(sc.hasNextInt()) {
        list.add(sc.nextInt());
        hset.put(count, new HashSet<>(list));   
        if("the program starts to read the next set"){
            count++;
            list.clear();
            }
       else if("there are no more inputs")
           break;
        }
}

//Example 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
publicstaticvoidmain(字符串[]args){
HashMap hset=新的HashMap();
扫描仪sc=新的扫描仪(System.in);
整数计数=1;
HashSet list=新的HashSet();
System.out.println(“输入数字”);
while(sc.hasnetint()){
添加(sc.nextInt());
hset.put(计数,新哈希集(列表));
如果(“程序开始读取下一组”){
计数++;
list.clear();
}
否则,如果(“没有更多输入”)
打破
}
}
//扫描仪输入示例
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

命名对代码读者有帮助的变量始终是一个很好的做法。在下面的代码中,我创建了一组数字,然后将其存储到一个映射中,其中key作为set的计数,value作为set本身。
如果用户输入asterix,程序将退出。我不是在处理数字格式异常之类的异常,因为我希望用户在每行中只放置空格分隔的数字。
一旦扫描仪接收到asterix(*),程序将退出,输出为地图值

import java.util.HashMap; import java.util.HashSet; import java.util.Scanner; public class Test { public static void main(String[] args) { HashMap> map = new HashMap(); Scanner sc = new Scanner(System.in); int count = 1; HashSet set = new HashSet(); String k = ""; while (k != "*") { System.out.println("Please enter the space separated numbers, or * to exit"); String sentence = sc.nextLine(); String[] strs = sentence.split(" "); if(strs[0].equals("*")) break; for (String s : strs) { set.add(Integer.valueOf(s)); } map.put(set.size(), set); } System.out.println(map); } } 导入java.util.HashMap; 导入java.util.HashSet; 导入java.util.Scanner; 公开课考试{ 公共静态void main(字符串[]args){ HashMap>map=新建HashMap(); 扫描仪sc=新的扫描仪(System.in); 整数计数=1; HashSet=newhashset(); 字符串k=“”; 而(k!=“*”){ System.out.println(“请输入空格分隔的数字,或*退出”); 字符串语句=sc.nextLine(); 字符串[]strs=句子。拆分(“”); 如果(strs[0]。等于(“*”)中断; 用于(字符串s:strs){ set.add(Integer.valueOf(s)); } map.put(set.size(),set); } 系统输出打印项次(map); } } 如果其中一个答案解决了您的问题,您可以通过将其标记为已接受来帮助社区。公认的答案有助于未来的访问者自信地使用解决方案。要进行此操作,您需要单击大复选标记(✓) 在答案的左边。注意:一个问题只能接受一个答案。但是,一旦你有15+个信誉点,你可以根据自己的意愿选择任意多个答案。