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 consideration the TimedScanner
class proposed 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 all possible words;
-
The Math.random
method is used to choose a random word from array
;
-
The original word is stored in the variable original
;
-
This word is made into a list and scrambled using the Collections.shuffle
method. Soon after this the result is transformed back into a String
;
-
The TimedScanner
class receives the statement by means of the nextLine
method to wait for data entry;
-
The variable digitada
is populated with the user input and then checked. If it is null
it means the user took more than 15 seconds to report the word. If it is SAIR
the looping
of the game will stop and the program will be finished. If it is the same as the chosen word or if the user misses the word a message will be displayed.