我需要验证用户输入,如果它不符合条件,那么我需要用正确的输入替换它。到目前为止,我被困在两个部分。我对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);