循环从扫描仪的不同行读取多个HashSet

循环从扫描仪的不同行读取多个HashSet

本文介绍了循环从扫描仪的不同行读取多个HashSet的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要让用户使用扫描仪并键入许多不同的HashSet,(下面是示例输入),我需要将所有这些都转换为不同的HashSet,然后将其保存到HashMap中.我的代码会将输入的数字放入HashSet中,但无法确定何时是下一个HashSet,也就无法确定何时出现下一个行集.

I am going to have the user use the Scanner and type in many different HashSets, (sample inputs are below) I need to turn all of these into different HashSets that will then be saved to a HashMap. My code will put the entered numbers into a HashSet but it unable to tell when is the next HashSet, that is it cannot tell when the next line set occurs.

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

推荐答案

命名变量总是一个好习惯,这将有助于代码阅读者.在下面的代码中,我将创建一组数字,然后将其存储到映射中,其中键为集合的计数,而值为集合本身.
如果用户输入星号,则程序将退出.我不处理数字格式异常之类的异常,因为我希望用户应该在每行中仅使用空格分隔数字.
扫描仪收到星号(*)后,程序将退出并输出为地图值.

It is always a good practice to name the variables that will be helpful to the reader of the code. In the following code, I am creating a set of numbers, which in turn I am storing to a map with key as the count of set and value as the set itself.
The Program will exit, if the user enters an asterix. I am not dealing with exceptions like Number format exception, as I am expecting the user should put only space separated numbers in each line.
Once the scanner receives, an asterix(*), the program will exit with output as the map values.



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

这篇关于循环从扫描仪的不同行读取多个HashSet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 15:24