Home > Software engineering >  How do I make this code easier? Without using Character.toString and boolean reapeat = false/reapeat
How do I make this code easier? Without using Character.toString and boolean reapeat = false/reapeat

Time:04-27

This is a guessing game.

You are to make a guessing game, in which the user will try to guess a secret word or phrase, one letter at a time. Your word/phrase should be printed out with underscores for each letter that is unguessed and spaces where any spaces would go. The number of letters in each word should appear in parentheses after the word so the user can tell how many letters there are. After a user guesses a letter, all instances of that letter in the secret word/phrase should be revealed. The user will have 5 incorrect guesses before they lose the game. When the player loses, the remaining letters should appear, revealing the secret word/phrase. Sample output below:

I want to make this code easier using some basic methods.

import java.util.Scanner;

public class guess {

    public static void main(String[] args) {
        int tries = 0;

        boolean reapeat = false;
        String guesses = "";
        String holder = "";

        Scanner keyboard = new Scanner(System.in);
        System.out.print("Enter your secret word: ");
        String word = keyboard.nextLine();


        while (tries < 10) {
            System.out.println("Enter your letter guess");
            String guess = keyboard.nextLine();

            for(int i = 0; i < word.length(); i   ) {
                if (guess.equals(Character.toString(word.charAt(i)))) {
                    if(!reapeat)
                        guesses  = Character.toString(word.charAt(i));
                    else {
                        holder = Character.toString(guesses.charAt(i)).replace("_", guess);
                        guesses = guesses.substring(0, i)   holder   guesses.substring( i   1, guesses.length());
                    }
                } else {
                    if(!reapeat) {
                        guesses  = "_";
                    }
                }
            }
            tries  ;
            reapeat = true;
            System.out.println(guesses);
            if(guesses.equals(word)) {
                System.out.println("You guessed correctly!");
                break;
            }
        }

    }
}

CodePudding user response:

You can transform your string into a string array using the split function for easier access to the individual characters.

String[] charArray = word.split("");

//example of accessing the character
if (guess.equals(charArray[i])) {}

//example of setting character value
charArray[i] = guess;

CodePudding user response:

Don't know if this is what you're looking for:

public class SecretWord {
    private char []display;
    private String word;
    private int maxGuess;
    private int guesses;
    
    public SecretWord(String word, int maxGuess) {
        this.word = word;
        this.maxGuess = maxGuess;
        guesses = 0;
        display = new char[word.length()];
        Arrays.fill(display, '_');
    }
    
    public void guess(char c) {
        guesses  ;
        for (int idx = word.indexOf(c, 0); idx >= 0; idx = word.indexOf(c, idx 1)) {
            display[idx] = c;
        }
    }
    
    public int guessesLeft() {
        return maxGuess - guesses;
    }
    
    public boolean isDone() {
        return guesses == maxGuess || isWin();
    }
    
    public boolean isWin() {
        return guesses < maxGuess && !new String(display).contains("_");
    }
    
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append(display);
        return builder.toString();
    }
    
    public static void main(String[] args) throws IOException {
        try (Scanner scanner = new Scanner(System.in)) {
            System.out.println("Enter Secret word: ");
            String word = scanner.next();
            SecretWord secretWord = new SecretWord(word, 10);
            while (!secretWord.isDone()) {
                System.out.printf("%d guesses left\n", secretWord.guessesLeft());
                System.out.println("Enter a letter: ");
                String guess = scanner.next();
                secretWord.guess(guess.toLowerCase().charAt(0));
                System.out.println(secretWord);
            }
            
            if (secretWord.isWin()) {
                System.out.println("You win!");
            } else {
                System.out.println("You lost.");
            }
        }
        
    }
}

CodePudding user response:

You could do something like this:

public class Guess {

    private final String word;
    private final Set<Character> characters;
    private final Set<Character> guessedCharacters;

    private Guess(String word) {
        this.word = word;
        this.characters = word.chars().mapToObj(i -> (char) i).collect(Collectors.toSet());
        this.guessedCharacters = new HashSet<>();
    }

    public void guessCharacter(Character character) {
        if (characters.contains(character)) {
            guessedCharacters.add(character);
        }
    }

    public boolean isSolved() {
        return guessedCharacters.containsAll(characters);
    }

    public String getMatches() {
        return word.chars().mapToObj(i -> (char) i)
                .map(c -> guessedCharacters.contains(c) ? c : '_')
                .map(Objects::toString)
                .collect(Collectors.joining());
    }

    public static void main(String[] args) {
        final int maxTries = 10;
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Enter your secret word: ");
        String word = keyboard.nextLine();
        final var guess = new Guess(word);

        for (var i = 1; i <= maxTries; i  ) {
            System.out.printf("Enter your letter guess #%d/%d: ", i, maxTries);
            Character character = keyboard.nextLine()
                    .chars().mapToObj(ch -> (char) ch)
                    .findFirst()
                    .orElse(null);

            guess.guessCharacter(character);
            System.out.println(guess.getMatches());
            if (guess.isSolved()) {
                System.out.println("You guessed correctly!");
                break;
            }
        }

    }
}
  • Related