Advertisement
Guest User

Untitled

a guest
Oct 18th, 2019
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.22 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class Exercise4v12 {
  4. private static final String EMPTY_SIGN = "_";
  5. private static String hideWord;
  6. private static String usersWord;
  7. private static int wordsLength;
  8. private static Scanner scanner;
  9.  
  10. public static void main(String[] args) {
  11. startGame();
  12. }
  13.  
  14. private static void startGame() {
  15. boolean isOut = false;
  16. int counter = 0;
  17.  
  18. initialize();
  19. System.out.printf("Угадайте слово из %d букв%n", wordsLength);
  20. while (!hideWord.equals(usersWord)) {
  21. showUsersWord();
  22. System.out.println("Введите букву слова. (0 - для выхода)");
  23. String userChar = getUserInput();
  24. if (userChar.equals("0")) {
  25. isOut = true;
  26. System.out.println("Вы прервали игру.");
  27. break;
  28. }
  29. counter++;
  30. System.out.printf("Вы ввели знак %s%n", userChar);
  31. if (checkChar(userChar)) {
  32. System.out.println("Верно, есть такая буква!");
  33. } else {
  34. System.out.println("Такой буквы в слове нет.");
  35. }
  36. }
  37. if (!isOut) {
  38. showUsersWord();
  39. System.out.printf("Поздравляем! Вы угадали слово с %d попытки.", counter);
  40. }
  41. }
  42.  
  43. private static boolean checkChar(String userChar) {
  44. int prevIndex = -1;
  45. int index = -1;
  46.  
  47. while ((index = hideWord.indexOf(userChar, index + 1)) != -1) {
  48. usersWord = usersWord.substring(0, index) + userChar + usersWord.substring(index + 1);
  49. prevIndex = index + 1;
  50. }
  51. return prevIndex != -1;
  52. }
  53.  
  54. private static String getUserInput() {
  55. String result = scanner.nextLine();
  56. return result.substring(0, 1);
  57. }
  58.  
  59. private static void initialize() {
  60. hideWord = "мухомором";
  61. wordsLength = hideWord.length();
  62. scanner = new Scanner(System.in);
  63. usersWord = hideWord.replaceAll(".", "_");
  64. }
  65.  
  66. private static void showUsersWord() {
  67. System.out.println(usersWord);
  68. }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement