[英]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";字符串测试 = "1 2 3 4 5 42"; String test2 = test.replaceAll(" ","");
字符串 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.您应该首先使用 split() 拆分输入参数。
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);
}
IllegalArgumentException
from Set.of
Set.of
捕获IllegalArgumentException
The Set.of
convenience method in Java 9+ creates a Set
of an unspecified implementation when passed an array. Java 9+ 中的
Set.of
便捷方法在传递数组时创建了一个未指定实现的Set
。 If any duplicates are encountered while building this Set
, an exception is thrown.如果在构建此
Set
时遇到任何重复项,则会引发异常。 You can trap for that IllegalArgumentException
to know if the parts of your string are distinct or not.您可以捕获该
IllegalArgumentException
以了解您的字符串的各个部分是否不同。
We can get an array of the parts of your string by calling String#split
.我们可以通过调用
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 .请参阅在 Ideone.com 上实时运行的代码。
Input is distinct: false
输入不同:假
By the time you are passing your String parameter to uniqueNumbers() it looks like当您将 String 参数传递给 uniqueNumbers() 时,它看起来像
1234542
Splitting it into char array takes each single character as a separate element, printing out the output immediately for instance gives:将其拆分为 char 数组将每个单个字符作为一个单独的元素,立即打印输出,例如:
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.因此,当将每个元素传递给集合时,它会发现 2 在索引 1 和 6 处重复。
One solution in this case would be to pass the original to split test using String's instance split().在这种情况下,一种解决方案是使用 String 的实例 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.