简体   繁体   中英

What is the best way to ensure that all inputs are all unique Numbers

Here is an example inputs:

String test = "1 2 3 4 5 42"; String test2 = test.replaceAll(" ","");

public static boolean uniqueNumbers(String test2) {
    char[] testEntries= test2.toCharArray();
    Set<Character> set = new HashSet<>();
    
    for (int i = 0 ; i < testEntries.length ; i++ ) {
        if(!set.add(testEntries[i])) {
            return false;
        }
    }
    return true;
}

Despite all are unique number, it will return as false. Is there a way to fix this?

You should split your input argument with split() at first.

String test = "1 2 3 4 5 42";
String[] origin = test.split(" ");
Set<String> check = new HashSet<>(Arrays.asList(origin));
for (String el : check) {
    System.out.println(el);
}

Catch IllegalArgumentException from Set.of

The Set.of convenience method in Java 9+ creates a Set of an unspecified implementation when passed an array. If any duplicates are encountered while building this Set , an exception is thrown. You can trap for that IllegalArgumentException to know if the parts of your string are distinct or not.

We can get an array of the parts of your string by calling String#split .

Boolean isDistinct;
try
{
    Set.of( "1 3 3 4 5 42".split( " " ) );
    isDistinct = Boolean.TRUE;
}
catch ( IllegalArgumentException e )
{
    isDistinct = Boolean.FALSE;
}

System.out.println( "Input is distinct: " + Objects.requireNonNull( isDistinct ) );

See this code run live at Ideone.com .

Input is distinct: false

By the time you are passing your String parameter to uniqueNumbers() it looks like

1234542

Splitting it into char array takes each single character as a separate element, printing out the output immediately for instance gives:

char[] testEntries = test2.toCharArray();
System.out.println(Arrays.toString(testEntries));
//output: [1, 2, 3, 4, 5, 4, 2]

So when passing each element to the set, it finds 2 repeated at index 1 and 6.

One solution in this case would be to pass the original to split test using String's instance split().

    String test = "1 2 3 4 5 42";
    String[] test2=test.split(" ");


    public static boolean uniqueNumbers(String testEntries[]) {

    Set<String> set = new HashSet<>();

    for (int i = 0; i < testEntries.length; i++) {
        if (!set.add(testEntries[i])) {
            return false;
        }
    }
    return true;
}

//output: true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM