I have implemented the following code to try and sort an ArrayList based on the arrangement of my variable, wordToGuess, without using the Comparator class. This works for Strings that have no duplicate letters like "hoarse".
However, the problem arises when I change wordToGuess into "stellar". I do realise that the issue stems from indexOutOfBoundExceptionError but I have thought over a whole day and cant seem to find a probable solution.
My main issue is shifting the whole word "stellar" into my orderedHint ArrayList while keeping both 'l's inside.
Any help is very appreciated!! If you have a better suggestion on how I can sort an ArrayList without using another Comparator class, I will most definitely learn from it! Looking forward to your answers! :D
import java.util.ArrayList;
import java.util.List;
public class ArrayListTest {
public static List<Character> hints = new ArrayList<Character>();
public static List<Character> orderedHint = new ArrayList<Character>();
public static String wordToGuess = "hoarse";
public static String word = "";
public static String fullWord = "";
public static void sortHintsArray() {
System.out.println("hints: " + hints);
System.out.println("orderedHint: " + orderedHint);
for(int i = 0;i<hints.size();i++)
{
int index = wordToGuess.indexOf(hints.get(i));
orderedHint.set(index,hints.get(i));
System.out.println();
System.out.printf("%d iteration: \n",i+1);
System.out.println("hints: " + hints);
System.out.println("orderedHint: " + orderedHint);
}
for(int i =0;i<wordToGuess.length();i++)
{
fullWord += orderedHint.get(i);
}
}
public static boolean checkCorrect() {
return fullWord == word;
}
public static void main(String[] args) {
hints.add('e');
hints.add('r');
hints.add('s');
hints.add('a');
hints.add('h');
hints.add('o');
orderedHint.add('e');
orderedHint.add('r');
orderedHint.add('s');
orderedHint.add('a');
orderedHint.add('h');
orderedHint.add('o');
sortHintsArray();
//System.out.println(hints);
System.out.println(fullWord);
}
}
OUTPUT:
hints: [e, r, s, a, h, o]
orderedHint: [e, r, s, a, h, o]
1 iteration:
hints: [e, r, s, a, h, o]
orderedHint: [e, r, s, a, h, e]
2 iteration:
hints: [e, r, s, a, h, o]
orderedHint: [e, r, s, r, h, e]
3 iteration:
hints: [e, r, s, a, h, o]
orderedHint: [e, r, s, r, s, e]
4 iteration:
hints: [e, r, s, a, h, o]
orderedHint: [e, r, a, r, s, e]
5 iteration:
hints: [e, r, s, a, h, o]
orderedHint: [h, r, a, r, s, e]
6 iteration:
hints: [e, r, s, a, h, o]
orderedHint: [h, o, a, r, s, e]
hoarse