Search code examples
javastringstringbuilder

Guessing symbols in a Sting word java


Got a String like:

String str = "###############";

Got guess word, for example:

String guess = "Java"

User must guess word:

User input:

Sava

Sring should be:

String str = "#a#a###########";

all right symbols placed on their indexes

String is immutable class.

I chose Stringbuilder

 for (int i = 0; i < length ; i++) {
    if (rnd.charAt(i) == guess.charAt(i) && rnd.charAt(i) != '#'){
       sb.append(rnd.charAt(i));
        }
   }

 System.out.println(sb);

 sb.delete(0, sb.length());

Stringbuilder add right symbols not on possition 'i', but on the last indexes.

Example:

guess word: Java

user input Sala:

System.out.println(sb);

###############aa

How I can achieve needed result? And what tools should I use?

needed result:

Example:
guess word Java:

user input Sala:


System.out.println(sb);
#a#a###########

Solution

  • Work like this:

    private static String word(){
        String guess = new Scanner(System.in).nextLine();
        return guess;
    }
    
    private static void guessWord(String[]arr) {
        int random = new Random().nextInt(arr.length);
        String rnd = arr[random];
    
        int length = 15;
    
        StringBuilder sb = new StringBuilder();
        String guess = "";
    
        int rndLength = length - rnd.length();
        int guessLength = length - guess.length();
    
    
        do {
            System.out.println("Enter a word: ");
            guess = word();
    
           if (sb.length() < length){
               for (int i = 0; i < length ; i++) {
                   sb.append("#");
               }
           }
    
            for (int i = 0; i < length  && i < rnd.length() && i < guess.length();  i++) {
                if (rnd.charAt(i) == guess.charAt(i)){
                    sb.setCharAt(i, rnd.charAt(i));
                    sb.delete(length, sb.length());
                }
            }
    
            if (rnd.equals(guess)){
                System.out.println("Guess word: " + rnd);
                break;
            }else if (!rnd.equals(guess)) {
                System.out.println(sb);
            }
        }while (!rnd.equals(guess));
    }