0

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

2
  • Your 'ideal' output for PEAR is incorrect: 'P' occurs at [0, 2], not [0, 1] Commented Apr 5, 2014 at 3:12
  • To the downvoter: please read the Help center. Homework or similar things are okay as a question if they indicate what work has been done so far and what the difficulty is. I think the OP has done that here. Commented Apr 5, 2014 at 3:21

2 Answers 2

1

You have your inner an outer loop mixed up, and you're using the wrong index (i or j) with the wrong array/string at times. It helps to give i and j more descriptive names so you know when to use which. And lastly, you can only print the "occurs" string after you've tried to find all occurrences, otherwise you are printing a whole line for every occurrence, instead of one line for all occurrences of a character.

This fixes your loop:

for (int stringIndex = 0; stringIndex < string.length(); stringIndex++) {
    char ch = Character.toUpperCase(string.charAt(stringIndex));
    List<Integer> letterList = new ArrayList<Integer>();
    for (int anArrayIndex = 0; anArrayIndex < anArray.length; anArrayIndex++) {
        if (anArray[anArrayIndex] == ch) {
            letterList.add(anArrayIndex);
        }
    }
    System.out.println(ch + " occurs at the following index " + letterList);
}

I'll leave it as an exercise for yourself to test whether letterList is empty (hint: look at Javadoc for method isEmpty()) and print a different message to indicate that you didn't find any occurrences.

Sign up to request clarification or add additional context in comments.

Comments

0
int i;
// Loop to find index of inputted character
// List to store the output
List<String> outList = new ArrayList<String> ();
char[] stringArray = string.toCharArray();    
for (char stringArrayChar: stringArray) {
    // StringBuilder to store output for each iteration
    StringBuilder sb = new StringBuilder();
    sb.append(Character.toUpperCase(stringArrayChar) + " occurs at ");

    // positions List
    List<Integer> posList = new ArrayList<Integer>();
    i = 0;
    for (char anArrayChar: anArray) {          
        if (anArrayChar == Character.toUpperCase(stringArrayChar)) {
           posList.add(i);              
        }
        i++;
    }
    // Check if the char is present in the specified array
    if (posList.size() > 0) { 
        sb.append(posList.toString());            
    } else {
        sb.append(" No Place in Array");
    }
    outList.add(sb.toString());
}
// Print the final result
for(String outString: outList ) {
    System.out.println(outString);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.