I'm attempting to achieve a simple sort of hangman situation in Java, where an array of characters is initialized, takes a user input, and returns all indexes where the letters in the string input occurs. So far, I have a very strange output and I think it's due to my beginner's faux pas in terms of my loops and certain placements. Do let me know if you have insight to this issue:
public class ArrayRandomString {
public static void main(String[] args) {
// Create an array of characters:
Character[] anArray = { 'P', 'A', 'P', 'A', 'B', 'E', 'A', 'R' };
for (char ch : anArray)
System.out.print(ch + " ");
System.out.println();
System.out.println("This program initializes a secret word or phrase to be guessed by you!");
System.out.println("Enter a string of less than 5 characters to return all indexes where it occurs in scrambled string: ");
Scanner input = new Scanner(System.in);
String string = input.next();
System.out.println(string);
System.out.println(Character.toUpperCase(string.charAt(0)));
List<Integer> myList = new ArrayList<Integer>();
List<Integer> noList = new ArrayList<Integer>();
int i;
int j;
// Loop to find index of inputted character
for (i = 0; i < anArray.length; i++) {
Character ch = new Character(anArray[i]);
for (j = 0; j < string.length(); j++) {
List<Integer> letterList = new ArrayList<Integer>();
if (Character.toUpperCase(string.charAt(j)) == ch) {
letterList.add(j);
}
System.out.println(Character.toUpperCase(string.charAt(j)) + " occurs at the following index " + letterList);
}
}
// System.out.println("Your letter occurs at the following index in the scrambled array. No occurence, if empty: " + myList);
}
}
If user input is 'PEAR', Ideal Output:
P occurs at [0, 2]
E occurs at [5]
A occurs at [1, 3, 6]
R occurs at [7]
If user input is 'TEA', Ideal Output:
T does not occur in string
E occurs at [5]
A occurs at [1, 3, 6]
So far, I haven't coded for "does not occur" since "does occur" is already so strange. Thanks in advance
[0, 2], not[0, 1]