有了你的問題,我假設你是Java的初學者,仍然在學習編程的基本概念。
您必須遵循以下步驟:
- 可以預先定義的範圍。上面的解決方案也可以工作。否則,您可以使用Java的
ValueRange
功能。
- 掃描輸入字符串。你可以使用
Scanner
。
- 掃描輸入字符串後,必須通過刪除逗號來分隔數字。
- 您必須將輸入數字映射到適當的範圍,並獲取每個範圍中輸入值的數量。
- 現在,你將不得不產生預期的輸出
下面的解決方案實現了使用Java8步驟(2-5)。學習這個實現對你也很有用。
public static void main(String[] args) {
//Define Range and their message in the output
Map<ValueRange, String> rangeToMessage = new LinkedHashMap<ValueRange, String>() {
{
put(ValueRange.of(0, 40), "R");
put(ValueRange.of(40, 60), "Lvl 1");
put(ValueRange.of(60, 70), "Lvl 2");
put(ValueRange.of(70, 80), "Lvl 3");
put(ValueRange.of(80, Integer.MAX_VALUE), "Lvl 4");
}
};
//Process Input String
String input = "12,32,56,76,89,87,78";
input.split(",");
List<String> strArray = Arrays.asList(input.split(","));
Function<Integer, Optional<ValueRange>> getRange = value -> rangeToMessage.keySet().stream()
.filter(t -> t.isValidIntValue(value)).findFirst();
//Map input numbers to their appropriate Range and get the number of input value in each Range
Map<ValueRange, Long> rangeNcount = strArray.stream().map(Integer::parseInt).map(getRange)
.filter(opt -> opt.isPresent()).map(opt -> opt.get())
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
//Produce expected output message
Function<ValueRange,Long> getCount = range-> (rangeNcount.get(range)==null)?Long.valueOf(0):rangeNcount.get(range);
String outputMessage = rangeToMessage.keySet().stream().map(range->rangeToMessage.get(range)+":"+getCount.apply(range)).collect(Collectors.joining(","));
System.out.println(outputMessage);
}
我希望我有你的問題。不過,讓我知道你是否需要任何幫助。 –
我得到它的工作,我可以幫你一點,你必須寫txtlevel == 80或它不會計算任何數字,如70,80,60 – jack
我可以使用幫助如何排序數組字符串 – jack