Help with scrambled words

Asked

Viewed 574 times

1

I need help in a program, I have no idea how to do, the statement is as follows:

"Scrambled Word - Implement a program that, from a word bank, randomly selects a word, shuffles the letters and gives the user time to guess the word."

I thought I’d use two String vectors, and one String so I could take one index from the main vector and put it in the other to be random, but it can generate a repeated Input.

  • Has any response helped solve the problem and can address similar questions from other users? If so, make sure to mark the answer as accepted. To do this just click on the left side of it (below the indicator of up and down votes).

1 answer

0


You can use the following implementation:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;

public class Embaralhar {

  private final String[] palavras = new String[]{"ACEROLA", "ABACATE", "ABACAXI", "AMEIXA",
    "AMORA", "BANANA", "CAJU", "CAQUI",
    "CARAMBOLA", "CEREJA", "DAMASCO", "FIGO",
    "FRAMBOESA", "GOIABA", "GRAVIOLA", "GROSELHA",
    "JABUTICABA", "JACA", "LARANJA", "MELANCIA",
    "MANGA", "MEXERICA", "MIRTILO", "MORANGO",
    "NECTARINA", "PEQUI", "PITANGA", "KIWI",
    "TAMARINDO", "TANGERINA", "UVA"};

  public static void main(String[] args) {
    Embaralhar embaralhar = new Embaralhar();
    TimedScanner scanner = new TimedScanner(System.in);
    String digitada;

    try {
      while (true) {
        String original = embaralhar.escolherPalavraAleatoria().toUpperCase();
        String embaralhada = embaralhar.embaralhar(original);
        System.out.println("A palavra embaralhada é: " + embaralhada);

        digitada = scanner.nextLine(15000);

        if (digitada == null) {
          System.out.println("Você levou mais de 15 segundos para inserir uma resposta. Seja mais rápido da próxima vez.");
        } else if (digitada.toUpperCase().equals("SAIR")) {
          System.out.println("Você escolheu sair do jogo. Até mais!");
          break;
        } else if (digitada.toUpperCase().equals(original)) {
          System.out.println("Você acertou a palavra \"" + original + "\" em menos de 15 segundos. Parabéns!");
        } else {
          System.out.println("Você errou. A palavra certa seria \"" + original + "\".");
        }
      }
    } catch (InterruptedException | ExecutionException ex) {
      Logger.getLogger(Embaralhar.class.getName()).log(Level.SEVERE, null, ex);
    }
  }

  private String escolherPalavraAleatoria() {
    return this.palavras[(int) (Math.random() * this.palavras.length)];
  }

  private String embaralhar(String palavra) {
    List<Character> letras = new ArrayList<>();

    palavra.chars()
            .mapToObj(x -> (char) x)
            .forEach(letras::add);

    Collections.shuffle(letras);

    return letras.stream()
            .map(e -> e.toString())
            .collect(Collectors.joining());
  }
}

This implementation takes into account the class TimedScanner proposal in this forum topic:

import java.io.InputStream;
import java.util.Scanner;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class TimedScanner {

  private final Scanner in;

  public TimedScanner(InputStream input) {
    in = new Scanner(input);
  }

  private final ExecutorService ex = Executors.newSingleThreadExecutor((Runnable r) -> {
    Thread t = new Thread(r);
    t.setDaemon(true);
    return t;
  });

  public String nextLine(int timeout) throws InterruptedException, ExecutionException {
    Future<String> result = ex.submit(new Worker());
    try {
      return result.get(timeout, TimeUnit.MILLISECONDS);
    } catch (TimeoutException e) {
      return null;
    }
  }

  private class Worker implements Callable<String> {

    @Override
    public String call() throws Exception {
      return in.nextLine();
    }
  }
}

In the proposed code:

  • A array of String is created with every possible word;

  • The method Math.random is used to choose a random word from array;

  • The original word is stored in the variable original;

  • This word is transformed into a list and shuffled using the method Collections.shuffle. Soon after this the result is transformed again into a String;

  • The class TimedScanner receive the instruction by the method nextLine to wait for data entry;

  • The variable digitada is populated with the user input and then checked. If null means that the user took more than 15 seconds to inform the word. If SAIR the looping game will stop and the program will be finished. If it is equal to the chosen word or if the user misses the word a message will be shown.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.