0

I am currently working on the below program. It takes 3 input words and outputs them in lexicographical order. I feel like I get an out of bounds exception because of some number I just entered incorrectly but I can't find it. Below is the code:

class LexicoOrder {
      public static void main(String[] args) {
         Scanner in = new Scanner(System.in);
                
        System.out.println("Enter a word: ");
        String firstword = in.nextLine();
        
        System.out.println("Enter another word: ");
        String secondword = in.nextLine();
        
        System.out.println("Enter one more word: ");
        String thirdword = in.nextLine();
         
    
        String[] words = {firstword, secondword, thirdword};
    
        for(int i = 0; i < 3; ++i) {
          for (int j = i + 1; j < 4; ++j) {
              
            if (words[i].compareTo(words[j]) > 0) { // receive error here. Out of bounds
    

              String temp = words[i];
              words[i] = words[j];
              words[j] = temp;
            }
          }
        }
    
        System.out.println("In lexicographical order:");
        
        for(int i = 0; i < 3; i++) {
          System.out.println(words[i]);
        }
      }
    }

If anyone can help find why I get this error with 3 words, it would be greatly appreciated.

  • 1
    Does this answer your question? [What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?](https://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) – maloomeister Nov 26 '21 at 08:02
  • You have three entries in `words`. Meaning, index 0, 1 and 2 are "in bounds" of the array. However, in your inner loop, you loop from `i+1` to `3`, and access your array with `words[j]`, which will in return cause the out of bounds due to the access from `words[3]`. – maloomeister Nov 26 '21 at 08:03
  • 1
    Instead of hardcoding values, use the size of the array as the loop condition (`i < words.length`). – maloomeister Nov 26 '21 at 08:04

1 Answers1

0
 for(int i = 0; i < 3; ++i) {
      for (int j = i + 1; j < 4; ++j) {
          
        if (words[i].compareTo(words[j]) > 0) 

problem is j will reach the point when it becomes 3, so words[3] is out of bound. use this instead :

 for(int i = 0; i < 3; ++i) {
      for (int j = i + 1; j < 3; ++j) {
          
        if (words[i].compareTo(words[j]) > 0) 

always keep in mind index starts at 0, so your indexes are 0, 1, 2 there is no 3.

Emad Ali
  • 107
  • 7