user2934559
user2934559

Reputation: 1

StringIndexOutOfRangeException

Im doing a simple program to check if user inputted words are a part of an alien language. Im getting an index out of range error message…any help? "String index out of range =" however many letters are inputted.

       import java.io.*;
       import java.util.*;
       import static java.lang.System.*;

    public class AlienWords{
       public static void main(String[]args) throws IOException {
       Scanner scan = new Scanner(in);

          out.print("Enter a word: ");
          String str = scan.nextLine();

          char d = str.charAt(str.length());

       int florb = 0;
       int zith = 0;
       int wooble = 0;
       int zarf = 0;

             if (str.charAt(0) == str.charAt(str.length())){
          florb++;
       }
             if (str.indexOf("cj") != -1 || str.indexOf("wq") != -1) {
          wooble++;
       }
             if (str.length() % 2 == 1 && str.indexOf('z') == -1){
          zith++;
       }
             if (str.length() % 2 == 0 && str.indexOf('k') == -1){
          zith++;
       }
             if(Character.isUpperCase(d)){
          zarf++;
       }
             else {
          out.println("This is not an alien word.");
             } 

          }
       }

Upvotes: 0

Views: 111

Answers (1)

nhgrif
nhgrif

Reputation: 62072

str.length()-1 is what you're looking for.

You said the error message you're getting is this: "String index out of range =" however many letters are inputted.. The "however many letters are inputted" in this case is your compiler telling you what index it attempted to access (but was out of range). Indexes for Strings start at 0, as such, the index of the last character will be 1 less than the total number of characters in the String.

Upvotes: 2

Related Questions