Streams
в Java может быть немного сложнее, но почему бы и нет?!
Вы можете определить универсальную функцию, работающую для любой последовательности:
static <T> T nthOrLastOrDefault(Collection<T> xs, int nth, T defaultValue) {
return xs.stream() // sequence as stream
.skip(nth - 1) // skip n - 1
.findFirst() // get next (the nth)
.orElse(xs.stream() // or if not available
.reduce(defaultValue, (a, b) -> b)); // replace defaultValue with the next and so on
}
Возвращая n-й элемент,если не последний, если не значение по умолчанию.
Теперь вы просто применяете эту функцию для всех слов, а затем для возвращаемого слова.
(К сожалению, Java управляет символами по-разному и должна быть преобразованаот целых чисел до символов)
String nthWord = nthOrLastOrDefault(asList(words), N, "");
List<Character> chars = nthWord.chars().mapToObj(i -> (char) i).collect(toList()); // ugly conversion
char nthNth = nthOrLastOrDefault(chars, N, '?');
Вывод может быть
Enter a line of words seperated by spaces:
one two three four five six
The nth char or last or default of the nth word or last or default is 'e'
Enter a line of words seperated by spaces:
one two three four
The nth char or last or default of the nth word or last or default is 'r'
Enter a line of words seperated by spaces:
The nth char or last or default of the nth word or last or default is '?'
Enter a line of words seperated by spaces:
(Полный пример кода)
static <T> T nthOrLastOrDefault(Collection<T> xs, int nth, T defaultValue) {
return xs.stream() // sequence as stream
.skip(nth - 1) // skip n - 1
.findFirst() // get next (the nth)
.orElse(xs.stream() // or if not available
.reduce(defaultValue, (a, b) -> b)); // replace defaultValue with the next and so on
}
public static void main(String[] args) {
final int N = 5;
try (final Scanner input = new Scanner(System.in)) {
while (true) {
System.out.println("Enter a line of words seperated by spaces:");
final String userInput = input.nextLine();
final String[] words = userInput.split(" ");
String nthWord = nthOrLastOrDefault(asList(words), N, "");
List<Character> chars = nthWord.chars().mapToObj(i -> (char) i).collect(toList()); // ugly conversion
char nthNth = nthOrLastOrDefault(chars, N, '?');
System.out.printf("The nth char or last or default of the nth word or last or default is '%c'%n", nthNth);
}
}
}