I'm playing the hangman game, and do I need to change a string for a char? but only one in a position

2

public class replace {

public static void main(String[] args) {
    Scanner teclado = new Scanner(System.in);
    String sentence = "SISAS";
    String auxWord = sentence;
    int g = sentence.length()*2;
    String remplazo = "_ ";
    while(remplazo.length()< g){
        remplazo += "_ ";
    }
    auxWord = remplazo;
    System.out.println(auxWord);
    int countWin=0 ;
    int countGAmeOver=0;
        while(auxWord != sentence){
        System.out.print("Ingrese una letra:");
        String y = teclado.nextLine();
        y = y.toUpperCase();
        char chary = y.charAt(0);
        for(int x=0;x<sentence.length();x++){
        if(sentence.charAt(x)== chary ){
                    countWin++;
                    System.out.println(auxWord.replace("_ ",y ));
                    System.out.println("acertada :" + countWin);
                    break;
        }
        }
        }
}
    
asked by Yeferson Gallo 22.07.2016 в 02:32
source

1 answer

2

The error you say is in this part of the code:

System.out.println(auxWord.replace("_ ",y ));

What you are doing is replacing each "_" with your new char and not with the position that you really want. You have to change your function so that it only changes the char in the position where there was character matching.

The new code would look like this:

public static void main(String[] args) {
    Scanner teclado = new Scanner(System.in);
    String sentence = "hola";
    String auxWord = sentence;
    int g = sentence.length() * 2;
    String remplazo = "_ ";
    while (remplazo.length() < g) {
        remplazo += "_ ";
    }
    auxWord = remplazo;
    System.out.println(auxWord);
    int countWin = 0;
    int countGAmeOver = 0;
    while (countWin != sentence.length()) {
        System.out.print("Ingrese una letra:");
        String letraIntroducida = teclado.nextLine().toUpperCase();
        char chary = letraIntroducida.charAt(0);
        for (int x = 0; x < sentence.length(); x++) {
            if (sentence.toUpperCase().charAt(x) == chary) {//Modifique acá, así compara los dos char en mayuscula.
                countWin++;//cambiar la posicion de x en el string por el char.
                auxWord = cambiarString(auxWord,chary,x*2);
                System.out.println("Nuevo string: " + auxWord);
                System.out.println("acertada :" + countWin);
            }
        }
    }

}

public static String cambiarString(String sentence,char newChar,int index) {
    char[] sequence = sentence.toCharArray();
    sequence[index] = newChar;
    return new String(sequence);
}

EXTRA:

Notice that you remove the break of the for loop. That way you get it fixed in all, for example, S of your sentence and not only in the first one you find.

    
answered by 22.07.2016 / 02:57
source