Advertisement
Guest User

Untitled

a guest
Jun 16th, 2019
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.58 KB | None | 0 0
  1. import java.util.Arrays;
  2. import java.util.Random;
  3. import java.util.Scanner;
  4.  
  5. /**
  6. * Java. Level 1. Lesson 3. Homework doing.
  7. *
  8. * @autor @Dmitriy Solonnikov
  9. * @version dated Jun-07-2019
  10. *
  11. * 1. Написать программу, которая загадывает случайное число от 0 до 9 и пользователю дается 3 попытки угадать это число.
  12. * При каждой попытке компьютер должен сообщить, больше ли указанное пользователем число, чем загаданное, или меньше.
  13. * После победы или проигрыша выводится запрос – «Повторить игру еще раз? 1 – да / 0 – нет»(1 – повторить, 0 – нет).
  14. */
  15.  
  16. public class Lesson3_HomeWork {
  17. static int ARRAY_LENGTH = 10;
  18.  
  19. public static void main(String[] args) {
  20. // int[] doommyArray = Arrays.copyOf(fillArray(ARRAY_LENGTH), fillArray(ARRAY_LENGTH).length); // сюда надо скопировать массив, чтобы он не генерился заново
  21. // int doommyIndex = fillRandomInt(ARRAY_LENGTH); // содержит случайную позицию массива
  22. int doommyElement = fillArray(ARRAY_LENGTH)[fillRandomInt(ARRAY_LENGTH)]; // возвращает элемент массива, соответcтвующий слуайному индексу массива
  23. int userNumber; // сюда сохраняется ответ пользователя, введенного в консоль
  24. boolean toRepeat = true; // ключ входа / выхода из while
  25. Scanner scanner = new Scanner(System.in);
  26.  
  27.  
  28. // System.out.println(Arrays.toString(doommyArray)); // Провека работы методов fillArray
  29. // System.out.println(doommyIndex); // Провека работы методов index (слуайный индекс элемента масссива)
  30. System.out.println(doommyElement); // Провека работы возврата значения массива по индексу
  31.  
  32. System.out.println("Угадайте число от 0 до 10");
  33.  
  34. while (toRepeat) {
  35. for (int counter = 0; counter < 3; counter++) {
  36.  
  37. System.out.print("Enter the number: ");
  38. userNumber = scanner.nextInt();
  39. if (userNumber == doommyElement) {
  40. System.out.println("Congratulations!!!!");
  41. break;
  42. } else if (counter < 2) {
  43. System.out.println("Try one more time. " + (2 - counter) + " rounds less");
  44. }
  45. System.out.println("You have no more tryes");
  46. }
  47. System.out.println("Do You want to repeat the game \n" + "Y / N:");
  48. if (repeatGame(scanner) == toRepeat){
  49. System.out.println("Game begin again \n");
  50. }else {
  51. System.out.println("Game over \n");
  52. toRepeat = false;
  53. }
  54. }
  55. }
  56. // метод возвращения случайного целого числа
  57. public static int fillRandomInt (int ints){
  58. Random random = new Random();
  59. int i = random.nextInt(ints);
  60. return i;
  61. }
  62. // метод заполнения массива данной длины [10] случайными целыми числами fillRandomInt
  63. public static int [] fillArray (int length) {
  64. int [] arr = new int[length];
  65. for (int a = 0; a < arr.length; a++) {
  66. arr[a] = fillRandomInt(length + 1); // сюда передается дипазон возвращения случайного числа
  67. }
  68. return arr;
  69. }
  70. // // метод генерации случайного индекса в массиве
  71. // public static int index (){
  72. // Random random = new Random();
  73. // int index = random.nextInt(fillArray().length);
  74. // return index;
  75. // }
  76. // метод повтора игры
  77. public static boolean repeatGame (Scanner scanner) {
  78. String answer = scanner.nextLine();
  79. while (answer.equals("N") || answer.equals("Y")) {
  80. if (answer.equals("N")) {
  81. return false;
  82. } else if (answer.equals("Y")) {
  83. return true;
  84. } else {
  85. System.out.println("Wrong button");
  86. }
  87. }
  88. return false; // до этого места цикл никогда не дойде, это просто заглушка
  89. }
  90. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement