Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class Exercise4v12 {
- private static final String EMPTY_SIGN = "_";
- private static String hideWord;
- private static String usersWord;
- private static int wordsLength;
- private static Scanner scanner;
- public static void main(String[] args) {
- startGame();
- }
- private static void startGame() {
- boolean isOut = false;
- int counter = 0;
- initialize();
- System.out.printf("Угадайте слово из %d букв%n", wordsLength);
- while (!hideWord.equals(usersWord)) {
- showUsersWord();
- System.out.println("Введите букву слова. (0 - для выхода)");
- String userChar = getUserInput();
- if (userChar.equals("0")) {
- isOut = true;
- System.out.println("Вы прервали игру.");
- break;
- }
- counter++;
- System.out.printf("Вы ввели знак %s%n", userChar);
- if (checkChar(userChar)) {
- System.out.println("Верно, есть такая буква!");
- } else {
- System.out.println("Такой буквы в слове нет.");
- }
- }
- if (!isOut) {
- showUsersWord();
- System.out.printf("Поздравляем! Вы угадали слово с %d попытки.", counter);
- }
- }
- private static boolean checkChar(String userChar) {
- int prevIndex = -1;
- int index = -1;
- while ((index = hideWord.indexOf(userChar, index + 1)) != -1) {
- usersWord = usersWord.substring(0, index) + userChar + usersWord.substring(index + 1);
- prevIndex = index + 1;
- }
- return prevIndex != -1;
- }
- private static String getUserInput() {
- String result = scanner.nextLine();
- return result.substring(0, 1);
- }
- private static void initialize() {
- hideWord = "мухомором";
- wordsLength = hideWord.length();
- scanner = new Scanner(System.in);
- usersWord = hideWord.replaceAll(".", "_");
- }
- private static void showUsersWord() {
- System.out.println(usersWord);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement