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.