Как я могу напечатать N-й символ N-го слова в строке? - PullRequest
1 голос
/ 26 сентября 2019

Я работаю над проблемой домашней работы, которая требует, чтобы N-ный символ был напечатан N-ным словом в той же строке без пробелов.Если N-е слово слишком короткое и не имеет N-го символа, программа должна напечатать последний символ этого слова.Если пользователь вводит пустое слово (простым нажатием), эти слова игнорируются.

(Мы еще не изучили методы, поэтому я не должен их использовать)

См. Код ниже, я не уверен, как заставить мой код печатать последний символ этогослово, если оно не имеет N-го символа.

import java.util.Scanner;

public class Words {

    public static void main(String[] args) {
        final int N=5;
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a line of words seperated by spaces ");
        String userInput = input.nextLine();
        String[] words = userInput.split(" ");
        String nthWord = words[N];

        for(int i = 0; i < nthWord.length();i++) {
            if(nthWord.length()>=N) {
                char nthChar = nthWord.charAt(N);
                System.out.print("The " + N + "th word in the line entered is " + nthWord + "The " + N + "th charecter in the word is " + nthChar);
            }
            if(nthWord.length()<N) {
                    char nthChar2 = nthWord.charAt(nthWord.length()-1);
                    System.out.print("The " + N + "th word in the line entered is " + nthWord + "The " + N + "th charecter in the word is " + nthChar2);
        }
        input.close();
    }

}
}

Когда я запускаю это, я получаю ошибку:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 5
    at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:47)
    at java.base/java.lang.String.charAt(String.java:702)
    at Words.main(Words.java:24)

Я ожидаю увидеть N-е слово и N-й символ в одной строке

Ответы [ 3 ]

3 голосов
/ 26 сентября 2019

Пользовательский ввод также может содержать менее N слов, верно?Первая проверка должна быть такой.

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.print("Enter a line of words seperated by spaces ");
    String userInput = input.nextLine();
    String[] words = userInput.split(" ");
    int n = words.length();
    System.out.print("Enter lookup word - N");
    int askedFor = input.nextInt();
    if (askedFor > n) {
        //your logic for this condition
        return;
    }
    String nthWord = words[askedFor-1];
    if (nthWord.length() < askedFor) print(nthWord.charAt(nthWord.length()-1));
    else print(nthWord.charAt(askedFor-1));
    input.close();
}
0 голосов
/ 26 сентября 2019

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);
        }
    }
}
0 голосов
/ 26 сентября 2019
//Considering line as your input
String[] words = line.split(" ");

//Check if Nth word exists
if(words.length < N){
 System.out.println("Nth word does not exists");
 return;
}

//Check if Nth character exists in Nth word
if(words[N-1].length() < N){
 System.out.println("Nth character in Nth word does not exists");
 return;
}

// returning Nth character from Nth word
// Here N-1 = N; as programming starts with 0th index
return words[N-1].charAt(N-1);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...