1

私は絞首刑執行人プログラムを作成しようとしています...他の問題とともに、文字の複数回の出現を見つけて、見つかったすべての出現を置き換える方法を見つけたり作成したりできないようです。この問題を解決しようとして、findAndReplace() メソッドをいじっていますが、うまくいきませんでした。誰か助けてください

public class Hangman {


static Scanner sc = new Scanner(System.in);
        static final int MAXTRYS = 10;
        static int numError = 0;
        static boolean FINSHED = false;
        String s;
        String input;
        String tW;
        int pos;


        public static void main(String[] args) {
            System.out.println("Welcome to the Hangman App" + "\n");
            String s = answerKey();
            StringBuilder AnswerKey = dashReplace(s);




            while(!FINSHED && numError < MAXTRYS){
            //get user input and cast to char
            System.out.println("Enter an Letter: ");
            String input = sc.nextLine();
            char ch = input.charAt(0);


            int pos = findAndReplace(s, AnswerKey, input, ch);
            int index = AnswerKey.indexOf("-");
            if(pos == -1){
                numError++;
                continue;
            }else if(index == -1){
                FINSHED = true;
                System.out.println("you won!");
            }
            }

        }


        public static int findAndReplace(String s, StringBuilder AnswerKey,
                String input, char ch) {
            //find position of user input and replace
            int pos = s.indexOf(input);
            AnswerKey.setCharAt(pos, ch);
           // while(pos > 0) {
           //    AnswerKey.setCharAt(pos, (char) (ch+1));
            //}
            System.out.println(AnswerKey);
            return pos;
        }


        public static StringBuilder dashReplace(String s) {
            //replace non-white space char with dashes and creates StringBuilder Object
            String tW = s.replaceAll("\\S", "-"); 
            System.out.print(tW + "\n");  
            StringBuilder AnswerKey = new StringBuilder(tW);
            return AnswerKey;
        }


        public static String answerKey() {
            //get random array element
            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);
            return s;
        }

}
4

2 に答える 2