【问题标题】:How to read a sequence of integers from Standard-input with Stdin?如何使用标准输入从标准输入中读取整数序列?
【发布时间】:2018-04-28 23:39:50
【问题描述】:

我在命令行上使用 java,我想编写一个程序来过滤和删除整数序列的重复项,但首先我不知道如何使用 StdIn 来读取整数序列。

程序应在 StdIn 的帮助下从标准输入读取值,直到到达 EOF 序列。

命令行输入输出示例:

$ echo 1 1 2 2 1 1 3 4 6 2 1 | java RemoveDuplicates
1 2 1 3 4 6 2 1

我尝试将整数转换为数组

int[] n = StdIn.readAllInts();

但在尝试打印时它不起作用。 有人可以给我一些提示吗?

【问题讨论】:

  • java RemoveDuplicates |回声 1 1 2 2 1 1 3 4 6 2 1 ?

标签: java stdin


【解决方案1】:

Stdin 不需要。

通过调用

java RemoveDuplicates 1 1 2 2 1 1 3 4 6 2 1 

它将String[] args 分配给所有这些值的数组。

如果要删除重复项,请将它们放入Set

public static void main(String[] args) {
    Set<String> uniq = new HashSet<>();
    for (String s : args) {
        uniq.add(s);
    }
    System.out.println(uniq);
}

【讨论】:

    【解决方案2】:

    下面的示例程序,这将删除重复的条目但仍保留顺序。

       public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the sequence with spaces e.g. 1 3 5 3 1 1 3 5 ");
        String input = sc.nextLine();
        String[] numbers = input.split("\\s+");
    
        List<String> result = new ArrayList<>();
        for (int x = 0; x < numbers.length; x++) {
            String item = numbers[x];
            if (result.contains(item)) continue;
            result.add(item);
        }
        System.out.println(String.join(" ", result));
    }
    

    输出样本为:

    Enter the sequence with spaces e.g. 1 3 5 3 1 1 3 5 
    1 1 2 2 1 1 1 3 4 1 1 1 11 11 12 12 1 1 6 6 2 1 //sequence entered
    1 2 3 4 11 12 6 // sample result
    

    【讨论】:

    • 您只删除连续的重复项
    【解决方案3】:

    可能的解决方案是:

        int testNum;
        Set<Integer> set = new HashSet<Integer>();
        Scanner in = new Scanner(System.in);
    
        System.out.println("number of elements to be inserted");
        testNum = in.nextInt();
    
    
    
    
        //Add items
        for ( int i = 0; i<testNum; i++)
        {
              set.add(in.nextInt());
        }
    
        //Print all element
        Iterator it = set.iterator();     
        while(it.hasNext()){
               System.out.println(it.next());
        }
    

    希望对你有所帮助

    【讨论】:

    • 更多信息参见java文档(Set,Iterator)
    【解决方案4】:

    您应该能够使用普通扫描仪将其作为字符串捕获:

    Scanner in = new Scanner(System.in);
    String line = in.nextLine();
    

    有时第二行不适用于某些输入,因此您也可以尝试:

    String line = in.next();
    

    要获得整数形式的数字,您可以使用 inputStream,但我不确定如何工作。

    【讨论】: