title: How do I print the Nth character of the Nth word in a line?
body: <p>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. </p>
  
  <p>(We haven't learned methods yet so I am not supposed to use them)</p>
  
  <p>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. </p>
  
  <pre class="lang-java prettyprint-override"><code>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 &lt; nthWord.length();i++) {
              if(nthWord.length()&gt;=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()&lt;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();
      }
  
  }
  }
  </code></pre>
  
  <p>When I run this I get an error: </p>
  
  <pre class="lang-java prettyprint-override"><code>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)
  </code></pre>
  
  <p>I expect to see the Nth word and the Nth character on the same line</p>