java—在循环中的不同行上从扫描器读取多个哈希集

uurv41yg  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(245)

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

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
o3imoua4

o3imoua41#

命名对代码读者有帮助的变量总是一个好的做法。在下面的代码中,我创建了一组数字,然后将其存储到一个map中,key作为set的计数,value作为set本身。
如果用户输入asterix,程序将退出。我没有处理像数字格式异常这样的异常,因为我希望用户应该在每行中只放置空格分隔的数字。
一旦扫描仪接收到星号(*),程序将退出,并输出Map值。

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); 
      }
    }

相关问题