This is a program where the user types a bunch of words and then the program rearranges them into alphabetical order and then prints them.
But this code keeps crashing on line 35 at "for (int count = 0; count < word1.length() ; count++)". Could anyone tell me whats wrong? (You can only input words that has the same length)
The error it gives is : java.lang.StringIndexOutOfBoundsException
it only gives the error when the user doesnt type it in alphabetical order. IDK why
Here is the code:
import java.awt.*; import hsa.Console; public class Alphabeticall_order { static Console c; // The output console public static void main (String[] args) { c = new Console (); c.println ("How many words do you want to put in?"); int slots = c.readInt (); String[] words = new String [slots]; for (int y = 0 ; y < slots ; y++) { c.println ("Input the words with the same length"); words [y] = c.readLine (); } for (int h = 0 ; h < slots ; h++) { for (int g = 0 ; g < slots - 1 ; g++) { words [g] = swaplow (words [g], words [g + 1]); words [g + 1] = swaphigh (words [g], words [g + 1]); } } for (int d = 0 ; d < slots ; d++) c.println (words [d]); } public static String swaplow (String word1, String word2) { String index = ""; for (int count = 0; count < word1.length() ; count++) { if (word1.charAt(count) < word2.charAt(count)) { index = word1; break; } else if (word1.charAt (count) > word2.charAt (count)) { index = word2; break; } } return index; } public static String swaphigh (String word1, String word2) { String index = ""; for (int count = 0; count < word1.length() ; count++) { if (word1.charAt (count) > word2.charAt (count)) { index = word1; break; } else if (word1.charAt (count) < word2.charAt (count)) { index = word2; break; } } return index; } }