Advertisement
dxvmxnd

1dopjava

Dec 4th, 2024
25
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.30 KB | None | 0 0
  1. import java.io.*;
  2. import java.util.Scanner;
  3.  
  4. public class Main {
  5. private static final Scanner scanner = new Scanner(System.in);
  6.  
  7. public static void main(String[] args) {
  8. int[] answerNumbers;
  9. int number;
  10.  
  11. taskEssence();
  12. number = sourceChoice();
  13. answerNumbers = checkForNumbers(number);
  14. output(answerNumbers);
  15. }
  16. public static int[] checkForNumbers(int number) {
  17. int countOfNumbers = 0;
  18. int maxExponent = 0;
  19.  
  20. while ((1 << maxExponent) - 1 < number) {
  21. maxExponent++;
  22. }
  23.  
  24. for (int i = 0; i < maxExponent; ++i) {
  25. int mersenneNumber = (1 << i) - 1; // 2^i - 1
  26. if (mersenneNumber < number) {
  27. countOfNumbers++;
  28. }
  29. }
  30.  
  31. int[] resultNumbers = new int[countOfNumbers];
  32. int index = 0;
  33.  
  34. // Заполняем массив числами Мерсенна
  35. for (int i = 0; i < maxExponent; ++i) {
  36. int mersenneNumber = (1 << i) - 1;
  37. if (mersenneNumber < number) {
  38. resultNumbers[index] = mersenneNumber;
  39. index++;
  40. }
  41. }
  42.  
  43. int[] answerNumbers = new int[countOfNumbers];
  44. System.arraycopy(resultNumbers, 0, answerNumbers, 0, countOfNumbers);
  45.  
  46. return answerNumbers;
  47. }
  48. public static void taskEssence() {
  49. System.out.println("Данная программа находит все числа Мерсенна, которые меньше введенного N.");
  50. }
  51. public static int sourceChoice() {
  52. int choiceNumber;
  53. boolean isIncorrect;
  54. choiceNumber = -1;
  55. int num;
  56.  
  57. System.out.println("Выберите, откуда будут вводиться данные: ");
  58. do {
  59. isIncorrect = false;
  60. System.out.println("Введите 0, если с консоли; 1, если с файла");
  61. try {
  62. choiceNumber = Integer.parseInt(scanner.nextLine());
  63. } catch (NumberFormatException exception) {
  64. isIncorrect = true;
  65. System.err.println("Неверный ввод данных!");
  66. }
  67. if (((choiceNumber != 0) && (choiceNumber != 1)) || (isIncorrect)) {
  68. isIncorrect = true;
  69. System.err.println("Число должно быть или 0, или 1");
  70. }
  71. } while (isIncorrect);
  72. if (choiceNumber == 0) {
  73. num = fromConsole();
  74. } else {
  75. num = fromFile();
  76. }
  77. return num;
  78. }
  79. public static int fromFile() {
  80. String path;
  81. int number;
  82.  
  83. path = pathChoice();
  84. number = numberReadFile(path);
  85. outputNumber(number);
  86.  
  87. return number;
  88. }
  89. public static String pathChoice() {
  90. String path;
  91. boolean isIncorrect;
  92.  
  93. do {
  94. isIncorrect = false;
  95. System.out.println("Введите путь к файлу: ");
  96. path = scanner.nextLine();
  97.  
  98. File file = new File(path);
  99. if (!file.exists()) {
  100. System.out.println("По указанном пути файл не найден.");
  101. isIncorrect = true;
  102. } else if (!getExtension(path).equals("txt")) {
  103. System.err.println("Ошибка, неправильный тип файла!");
  104. isIncorrect = true;
  105. }
  106. } while (isIncorrect);
  107. return path;
  108.  
  109. }
  110. public static String getExtension(String path) {
  111. int pos = path.lastIndexOf('.');
  112. if (pos <= 0) {
  113. return "";
  114. }
  115. return path.substring(pos + 1);
  116. }
  117. public static int numberReadFile(String path) {
  118. boolean isIncorrect;
  119. int number = 0;
  120.  
  121. System.out.println("Считывание числа...");
  122.  
  123. isIncorrect = false;
  124. try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
  125. try {
  126. number = Integer.parseInt(reader.readLine());
  127. } catch (NumberFormatException exception) {
  128. isIncorrect = true;
  129. }
  130. if(isIncorrect || (number < 1)) {
  131. System.out.println("Неверный ввод данных! Запишите данные с клавиатуры.");
  132. number = fromConsole();
  133. }
  134. } catch (IOException ioException) {
  135. isIncorrect = true;
  136. System.err.println("Ошибка!");
  137. }
  138.  
  139.  
  140. return number;
  141. }
  142. public static void output(int[] answerNumbers) {
  143. String path;
  144. boolean isIncorrect;
  145.  
  146. System.out.println("Найденные числа Мерсенна: " );
  147. for (int i = 0; i < answerNumbers.length; i++) {
  148. System.out.println(answerNumbers[i]);
  149. }
  150. path = outputPath();
  151. do {
  152. isIncorrect = false;
  153. try (FileWriter writer = new FileWriter(path, true)) {
  154. writer.write("Найденные числа Мерсенна: \n" );
  155. for (int i = 0; i < answerNumbers.length; i++) {
  156. writer.write(Integer.toString(answerNumbers[i]));
  157. }
  158. } catch (IOException ioException) {
  159. System.err.println("Ошибка при записи в файл");
  160. isIncorrect = true;
  161. }
  162. } while (isIncorrect);
  163. System.out.println("Данные записаны в файл.");
  164. }
  165. public static String outputPath() {
  166. String path;
  167. boolean isIncorrect;
  168.  
  169. do {
  170. isIncorrect = false;
  171. System.out.println("Введите путь к файлу для вывода: ");
  172. System.out.println();
  173. path = scanner.nextLine();
  174.  
  175. File file = new File(path);
  176. if (!file.exists()) {
  177. System.out.println("По указанном пути файл не найден.");
  178. isIncorrect = true;
  179. } else if (!getExtension(path).equals("txt")) {
  180. System.err.println("Ошибка, неправильный тип файла!");
  181. isIncorrect = true;
  182. }
  183. } while (isIncorrect);
  184. return path;
  185. }
  186. public static int fromConsole() {
  187. int number = 0;
  188. boolean isIncorrect;
  189.  
  190. do {
  191. isIncorrect = false;
  192. System.out.println("Введите натуральное число:");
  193. try {
  194. number = Integer.parseInt(scanner.nextLine());
  195. } catch(NumberFormatException exception) {
  196. isIncorrect = true;
  197. }
  198. if(isIncorrect || (number < 1)) {
  199. System.out.println("Ошибка! Повторите попытку.");
  200. isIncorrect = true;
  201. }
  202. } while(isIncorrect);
  203.  
  204. outputNumber(number);
  205.  
  206. return number;
  207.  
  208. }
  209. public static void outputNumber(int number) {
  210. System.out.println("Введенное число:");
  211. System.out.println(number);
  212. }
  213. }
  214.  
  215.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement