简体   繁体   English

如何使Java从命令行参数输出唯一整数?

[英]How do I get Java to output unique integers from a command-line argument?

The code below checks to ensure the command-line arguments are integers? 下面的代码检查以确保命令行参数为整数? However, I need it to only print each integer in the command line once, regardless of how many times that integer appears in the command line. 但是,我需要它仅在命令行中打印每个整数一次,而不管该整数在命令行中出现多少次。 How do I do that? 我怎么做?

public class Unique {
    public static void main(String[] args) {
        for (int i = 0; i<args.length; i++) {
            try {
                int j = Integer.parseInt(args[i]);
                System.out.println(j);
            }
            catch (NumberFormatException e) {
                System.out.println("Your command line argument "+ args[i] +" is a non-integer!");
            }
        }
    }
}

What you need is a Set. 您需要的是一套。 A set does not contain duplicates, as it is defined mathematically. 集合不包含重复项,因为它是数学定义的。 Java has a Set class that does that job. Java具有完成该工作的Set类。

Set<Integer> set = new HashSet<Integer>();
for (int i = 0; i < args.length; i++)
{
    try
    {
        int j = Integer.parseInt(args[i]);
        set.add(j);
    }
    catch (NumberFormatException e)
    {
        System.out.println("Your command line argument "+ args[i] +" is a non-integer!");
    }
}
System.out.println(set);

Or iterate over all the elements like this: 或遍历这样的所有元素:

for (Integer i : set)
{
    System.out.println(i);
}
public class Unique {

public static void main(String[] args) {

    final Set<Integer> uniqueIntegers = new HashSet<>();        

    for (int i = 0; i<args.length; i++) {
        try {
            int j = Integer.parseInt(args[i]);
            uniqueIntegers.add(j);
        }
        catch (NumberFormatException e) {
            System.out.println("Your command line argument "+ args[i] +" is a non-integer!");
        }
    }

    System.out.println(uniqueIntegers);
}
public class UniqueNumbers {
  public static void main(String[] args) {
    args = new String[6];
    args[0] = "5";
    args[1] = "6";
    args[2] = "2";
    args[3] = "5";
    args[4] = "1";
    args[5] = "1";

    Arrays.sort(args); 
   // Sort the array. This will use natural order:
   // low -> high for integers, a -> z and low to high for strings
   // Essentially this causes our array to sort from low to high, despite not being integers

    for (int i = 0; i < args.length; i++) { // Loop over the entire array
        if (i == 0) { // (1)
            System.out.println(args[0]);
        } else if (!(args[i - 1].equals(args[i]))) { // (2)
            System.out.println(args[i]);
        }
    }
  }
}

Output: 输出:

1
2
5
6

Clarification: 澄清:

To make it easy to demonstrate, I've manually placed the values into the array. 为了便于演示,我将值手动放入了数组中。 This makes no difference, you can just keep using your input method. 这没有什么区别,您可以继续使用输入法。

(1): Read (2) first. (1):首先阅读(2) Because of the method below, we would essentially skip the first element. 由于下面的方法,我们实际上将跳过第一个元素。 The second part of the else if essentially means if i > 0 . else if的第二部分, else if本质上表示if i > 0 If we wouldn't do this, we would get an ArrayIndexOutOfBoundsException when we do args[i - 1] because that would try to access args[-1] . 如果我们不这样做,则在执行args[i - 1]时会得到ArrayIndexOutOfBoundsException ,因为这将尝试访问args[-1] That's why we skip the first element: to avoid this. 这就是为什么我们跳过第一个元素:避免这种情况。 However, this would also mean that our first value ( 1 ) would be ignored. 但是,这也意味着我们的第一个值( 1 )将被忽略。 That's why we just want to make sure the first value is always printed. 这就是为什么我们只想确保始终打印第一个值。

(2): Now we check if the current element ( args[i] ) is equal ( .equals() ) to the previous elements ( args[i -1] ). (2):现在我们检查当前元素( args[i] )是否等于先前元素( args[i -1] )(. .equals() )。 If this is not the case ( ! inverts a statement), we print the current value. 如果不是这种情况( !反转一条语句),我们将打印当前值。

With this method, you can solve your assignment without any datastructures apart from the the standard one. 使用这种方法,您可以在没有标准结构之外的任何数据结构的情况下解决分配问题。

More visualization: 更多可视化:

Start: 开始:

5 6 2 5 1 1

Sort: 分类:

1 1 2 5 5 6

Loop: 环:

!  
1 1 2 5 5 6 -> Output: 1

  !
1 1 2 5 5 6 -> Not different from previous one, no output

    !
1 1 2 5 5 6 -> Different from previous one, output: 1 2

      !
1 1 2 5 5 6 -> Different from previous one, output 1 2 5

        !
1 1 2 5 5 6 -> Not different from previous one, no output

          !
1 1 2 5 5 6 -> Different from previous one, output 1 2 5 6

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将命令行输入文件中的行打印到命令行输出文件? - How do I print lines from a command-line input file to a command-line output file? 如果子进程是Java程序(带有命令行参数),如何从subprocess.check_output获取输出? - How can I get output from subprocess.check_output if the subprocess is a java program(with Command-line arguments)? 如何从命令行作为参数输入的文本文件中读取逗号分隔的字符串? - How do I read in comma separated string from text file that is inputted from command-line as argument? 使用Java捕获命令行输出 - Capturing command-line output using Java 如何使用YourKit Java Profiler连接到Java命令行工具? - How do I connect to a Java command-line tool with the YourKit Java Profiler? 未指定整数命令行 - Unspecified integers command-line 如何使用星号等在命令行Java程序中屏蔽密码? - How do I mask passwords in a command-line Java program with asterisks or the like? 如何将在命令行中输入的IP地址传递给Java中的客户端套接字构造函数? - How do I pass the IP address typed in the command-line to the client socket constructor in Java? 如何使程序允许在命令行上输入以空格分隔的整数列表(JAVA) - How to make program allow as input on the command-line a space-separated list of integers (JAVA) 如何从命令行Java中的args中提取两个路径? - How to extract two Paths from args in command-line Java?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM