Advertisement
believe_me

Untitled

Oct 29th, 2021
228
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 8.25 KB | None | 0 0
  1. package lab24;
  2.  
  3. import java.io.*;
  4. import java.text.DecimalFormat;
  5. import java.util.Scanner;
  6.  
  7. public class Main {
  8.  
  9.     static Scanner consoleScanner = new Scanner(System.in);
  10.  
  11.     public static void main(String[] args) {
  12.         int userWay;
  13.         double maxFunctionValue;
  14.         String formattedMaxFunctionValue;
  15.         System.out.println("Программа находит максимальное значение функции y=(2x + 3)/(2x^2 - 3x + 4) на отрезке [a,b]");
  16.         userWay = chooseWayOfInput();
  17.         int[] range = receiveRange(userWay);
  18.         sortRange(range);
  19.         maxFunctionValue = searchMaxFunctionValue(range);
  20.         formattedMaxFunctionValue = formatValue(maxFunctionValue);
  21.         resultOutput(formattedMaxFunctionValue, range);
  22.         userWayOfOutput(formattedMaxFunctionValue, range);
  23.         consoleScanner.close();
  24.         System.out.println("Программа завершена.");
  25.     }
  26.  
  27.     public static int inputNumber(int minNumber, int maxNumber) {
  28.         Scanner consoleScanner = new Scanner(System.in);
  29.         boolean isIncorrect;
  30.         int number = 0;
  31.         do {
  32.             isIncorrect = false;
  33.             try {
  34.                 number = Integer.parseInt(consoleScanner.nextLine());
  35.             } catch (Exception ex) {
  36.                 System.out.println("Число должно быть являться целым и быть не меньше " + minNumber + " и не больше, чем " + maxNumber);
  37.                 isIncorrect = true;
  38.             }
  39.             if (!isIncorrect && (number < minNumber || number > maxNumber)) {
  40.                 System.out.println("Число должно быть не меньше " + minNumber + " и не больше, чем " + maxNumber);
  41.                 isIncorrect = true;
  42.             }
  43.         } while (isIncorrect);
  44.         return number;
  45.     }
  46.  
  47.     static int chooseWayOfInput() {
  48.         int userWay;
  49.         final int consoleNumber = 1;
  50.         final int fileNumber = 2;
  51.         do {
  52.             System.out.println("Выберите способ ввода: \nНажмите '1', если хотите ввести отрезок [a,b] через консоль.\nНажмите '2', если хотите считать отрезок [a,b] из файла.");
  53.             userWay = inputNumber(1, 2);
  54.         } while (userWay != consoleNumber && userWay != fileNumber);
  55.         return userWay;
  56.     }
  57.  
  58.     static String inputPathToFile() {
  59.         System.out.println("Введите путь к файлу:");
  60.         boolean isIncorrect, isCorrect;
  61.         String path;
  62.         do {
  63.             do {
  64.                 isIncorrect = false;
  65.                 path = consoleScanner.nextLine();
  66.                 try {
  67.                     new FileReader(path);
  68.                 } catch (FileNotFoundException e) {
  69.                     System.out.println("Файл не найден. Введите путь к файлу еще раз:");
  70.                     isIncorrect = true;
  71.                 }
  72.             } while (isIncorrect);
  73.             isCorrect = checkExtension(path);
  74.         } while (!isCorrect);
  75.         return path;
  76.     }
  77.  
  78.     static int[] receiveRangeFromFile(String path) {
  79.         boolean isIncorrect;
  80.         int xStart = 0;
  81.         int xEnd = 0;
  82.         File file = new File(path);
  83.         do {
  84.             isIncorrect = false;
  85.             try {
  86.                 Scanner fileScanner = new Scanner(file);
  87.                 xStart = fileScanner.nextInt();
  88.                 xEnd = fileScanner.nextInt();
  89.                 fileScanner.close();
  90.             } catch (Exception ex) {
  91.                 System.out.println("Некорректные данные в файле.");
  92.                 path = inputPathToFile();
  93.                 isIncorrect = true;
  94.             }
  95.             if (Math.abs(xStart) > 100 || Math.abs(xEnd) > 100) {
  96.                 isIncorrect = true;
  97.                 System.out.println("Некорректные данные в файле.");
  98.                 path = inputPathToFile();
  99.             }
  100.         } while (isIncorrect);
  101.         return new int[]{xStart, xEnd};
  102.     }
  103.  
  104.     static void sortRange(int[] range) {
  105.         if (range[0] > range[1]) {
  106.             range[0] = range[0] + range[1];
  107.             range[1] = range[0] - range[1];
  108.             range[0] = range[0] - range[1];
  109.         }
  110.     }
  111.  
  112.     static int[] receiveRange(int userWay) {
  113.         String path;
  114.         int[] range = null;
  115.         switch (userWay) {
  116.             case 1: {
  117.                 range = receiveRangeFromConsole();
  118.                 break;
  119.             }
  120.             case 2: {
  121.                 path = inputPathToFile();
  122.                 range = receiveRangeFromFile(path);
  123.             }
  124.         }
  125.         return range;
  126.     }
  127.  
  128.     static double searchMaxFunctionValue(int[] range) {
  129.         double maxValue, y, x;
  130.         x = range[0];
  131.         maxValue = (2 * x) / (2 * x * x - 3 * x + 4);
  132.         while (x <= range[1]) {
  133.             y = (2 * x + 3) / (2 * x * x - 3 * x + 4);
  134.             x += 0.01;
  135.             if (y > maxValue) {
  136.                 maxValue = y;
  137.             }
  138.         }
  139.         return maxValue;
  140.     }
  141.  
  142.     static String formatValue(double maxFunctionValue) {
  143.         DecimalFormat decimalFormat = new DecimalFormat("#.###");
  144.         return decimalFormat.format(maxFunctionValue);
  145.     }
  146.  
  147.     static void resultOutput(String formattedMaxFunctionValue, int[] range) {
  148.         System.out.println("Наибольшее значение функции y=(2x + 3)/(2x^2 - 3x + 4) на отрезке [" + range[0] + "," + range[1] + "] = " + formattedMaxFunctionValue);
  149.     }
  150.  
  151.     static int[] receiveRangeFromConsole() {
  152.         int xStart, xEnd;
  153.         System.out.println("Введите первую границу отрезка");
  154.         xStart = inputNumber(-100, 100);
  155.         System.out.println("Введите вторую границу отрезка");
  156.         xEnd = inputNumber(-100, 100);
  157.         return new int[]{xStart, xEnd};
  158.     }
  159.  
  160.     static boolean checkPermission(String path) {
  161.         File file = new File(path);
  162.         if (!file.canWrite()) {
  163.             System.out.println("Файл закрыт для записи");
  164.             return false;
  165.         }
  166.         return true;
  167.     }
  168.  
  169.     static boolean checkExtension(String path) {
  170.         int lastIndex;
  171.         lastIndex = path.length() - 1;
  172.         char[] pathToFile = path.toCharArray();
  173.         if (pathToFile[lastIndex] != 't' || pathToFile[lastIndex - 1] != 'x' || pathToFile[lastIndex - 2] != 't' || pathToFile[lastIndex - 3] != '.') {
  174.             System.out.println("Файл имеет неверное расширение. ");
  175.             return false;
  176.         }
  177.         return true;
  178.     }
  179.  
  180.     static void checkOutputFile(String path) {
  181.         boolean isIncorrect;
  182.         do {
  183.             isIncorrect = false;
  184.             if (!checkPermission(path) || !checkExtension(path)) {
  185.                 isIncorrect = true;
  186.                 path = inputPathToFile();
  187.             }
  188.         } while (isIncorrect);
  189.     }
  190.  
  191.     static void printResultInFile(String path, String formattedMaxFunctionValue, int[] range) {
  192.         try {
  193.             FileWriter writer = new FileWriter(path);
  194.             writer.write("Наибольшее значение функции y=(2x + 3)/(2x^2 - 3x + 4) на отрезке [" + range[0] + "," + range[1] + "] = " + formattedMaxFunctionValue);
  195.             writer.flush();
  196.             writer.close();
  197.         } catch (IOException e) {
  198.             e.printStackTrace();
  199.         }
  200.     }
  201.  
  202.     static void userWayOfOutput(String formattedMaxFunctionValue, int[] range) {
  203.         String userWay;
  204.         char checkUserWay;
  205.         System.out.println("Если хотите записать результат в файл, введите '1'. Если не хотите - введите другой символ:");
  206.         userWay = consoleScanner.nextLine();
  207.         checkUserWay = userWay.charAt(0);
  208.         if (checkUserWay == '1') {
  209.             String path = inputPathToFile();
  210.             checkOutputFile(path);
  211.             printResultInFile(path, formattedMaxFunctionValue, range);
  212.             System.out.println("Результат записан в файл. \n");
  213.         }
  214.     }
  215. }
  216.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement