我需要验证用户输入,如果它不满足条件,那么我需要用正确的输入替换它。到目前为止,我被困在两个部分。我对 java8 还很陌生,对所有的库都不太熟悉,所以如果你能给我建议在哪里阅读更多关于这些的内容,我将不胜感激。
List<String> input = Arrays.asList(args);
List<String> validatedinput = input.stream()
.filter(p -> {
if (p.matches("[0-9, /,]+")) {
return true;
}
System.out.println("The value has to be positve number and not a character");
//Does the new input actually get saved here?
sc.nextLine();
return false;
}) //And here I am not really sure how to map the String object
.map(String::)
.validatedinput(Collectors.toList());
这种类型的逻辑不应该用流来完成,while
循环将是一个很好的候选者。
首先,让我们将数据分成两个列表,一个列表表示有效输入,另一个表示无效输入:
Map<Boolean, List<String>> resultSet =
Arrays.stream(args)
.collect(Collectors.partitioningBy(s -> s.matches(yourRegex),
Collectors.toCollection(ArrayList::new)));
然后创建 while 循环以要求用户更正所有无效输入:
int i = 0;
List<String> invalidInputs = resultSet.get(false);
final int size = invalidInputs.size();
while (i < size){
System.out.println("The value --> " + invalidInputs.get(i) +
" has to be positive number and not a character");
String temp = sc.nextLine();
if(temp.matches(yourRegex)){
resultSet.get(true).add(temp);
i++;
}
}
现在,您可以收集所有有效输入的列表并使用它做您喜欢的事情:
List<String> result = resultSet.get(true);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句