Comment puis-je imprimer le Nième caractère du mot Nième en ligne?

Molly McDonough:

Je travaille sur un problème de travail qui demande que le caractère impriment Nième le mot Nième sur la même ligne sans espaces. Si le mot Nième est trop court et ne pas Nième caractère, le programme imprime le dernier caractère de ce mot. Si l'utilisateur saisit un mot vide (presses simples), ne seront pas prises que les mots.

(Nous avons pas appris les méthodes pourtant si je ne suis pas censé les utiliser)

Voir le code ci-dessous, je ne suis pas sûr de savoir comment obtenir mon code pour imprimer le dernier caractère de ce mot si elle n'a pas le caractère Nième.

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();
    }

}
}

Quand je lance ce que je reçois une erreur:

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)

Je me attends de voir le mot Nième et le caractère Nième sur la même ligne

Yogesh Kaushik:

Entrée utilisateur peut également contenir moins de N mots, non? Vérifiez tout d'abord que devrait être.

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();
}

Je suppose que tu aimes

Origine http://43.154.161.224:23101/article/api/json?id=332856&siteId=1
conseillé
Classement