How do I print the Nth character of the Nth word in a line?

Molly McDonough :

I am working on a homework problem which requests that print the Nth character the Nth word on the same line with no spaces. If the Nth word is too short and does not have Nth character, the program shall print the last character of that word. If the user enters an empty word (simple presses), that words shall be disregarded.

(We haven't learned methods yet so I am not supposed to use them)

See the code below, I am not sure how to get my code to print the last character of that word if it does not have the Nth character.

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

}
}

When I run this I get an error:

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)

I expect to see the Nth word and the Nth character on the same line

Yogesh Kaushik :

User input can also contain less than N words, right? First check should be that.

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325789&siteId=1