Search code examples
javaarraysstoring-data

replace dash by position with user input then store


I'm working on a hangman app right now. I am now to Programming and am Trying at the moment to replace a dash in tW by position (pos) with the user input (input) then store the array... I can't find the issue and its driving me insane!!! please someone help me?

public static void main(String[] args) {
    //get random array element
    System.out.println("Welcome to the Hangman App");
    String array[] = new String[10];
    array[0] = "Hamlet";
    array[1] = "Mysts of Avalon";
    array[2] = "The Iliad";
    array[3] = "Tales from Edger Allan Poe";
    array[4] = "The Children of Hurin";
    array[5] = "The Red Badge of Courage";
    array[6] = "Of Mice and Men";
    array[7] =  "Utopia"; 
    array[8] =  "Chariots of the Gods";
    array[9] =  "A Brief History of Time";

    ArrayList<String> list = new ArrayList<String>(Arrays.asList(array));
    Collections.shuffle(list);
    String s = list.get(0);
    //for testing
    System.out.println(s);


    //replace non-white space char with dashes
    String tW = s.replaceAll("\\S", "-");   

    //get user input
    System.out.println("Enter an Letter: ");
    String input = sc.next();

    //find position of user input and replace
    int pos = s.indexOf(input);
    char ch = input.charAt(pos);
    char[] answer = tW.toCharArray();
    //answer[pos] = input;

    //test 
    System.out.println(answer);


}

Solution

  • char inp = input.charAt(0);
    //find position of user input and replace
    char[] answer = tW.toCharArray();
    for(int i = 0; i < answer.length; i++){
        if(s.charAt(i) == inp)
            answer[i] = inp;
    }
    

    Now it is working but only for one character. You should encapsulate it with while loop i.e

    int numError = 0;
    int maxError = a_number; 
    boolean finished = false; 
    while(!finished && numError < maxError){
        do_all_the_things_you_are_doing_now;
    
        if(ch is not exist in answer)
            numError++;
    
        else{
            if(there is no "_" in answer)
                 finished = true;
        }
    }