Advertisement
Vanya_Shestakov

laba2.2 (Java)

Oct 6th, 2020
217
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.13 KB | None | 0 0
  1. package com.company;
  2. import java.io.*;
  3. import java.util.Scanner;
  4.  
  5. public class Main {
  6.  
  7.     public static String inputPath(){
  8.         Scanner scan = new Scanner(System.in);
  9.         boolean isIncorrect;
  10.         String path;
  11.  
  12.         System.out.println("Введите абсолютную ссылку на файл");
  13.         do {
  14.             isIncorrect = false;
  15.             path = scan.nextLine();
  16.             File outputFile = new File(path);
  17.  
  18.             if (!outputFile.exists()){
  19.                 System.out.println("Файл не найден! Введите абсолютную ссылку на файл");
  20.                 isIncorrect = true;
  21.             }
  22.         }while (isIncorrect);
  23.         return path;
  24.     }
  25.  
  26.     public static int findSumOfDividers(int number){
  27.         int sum = 0;
  28.         for (int i = 1; i < number; i++){
  29.             if (number % i == 0){
  30.                 sum += i;
  31.             }
  32.         }
  33.         return sum;
  34.     }
  35.  
  36.     public static void outputToFile(String path) throws Exception {
  37.         FileWriter writer = new FileWriter(path);
  38.  
  39.         int firstNumber;
  40.         int secondNumber;
  41.         boolean notRepeatNumbers = true;
  42.  
  43.         for (int i = 1; i < 32000; i++){
  44.             firstNumber = findSumOfDividers(i);
  45.             secondNumber = findSumOfDividers(firstNumber);
  46.  
  47.             if ((i == secondNumber) && (secondNumber != firstNumber)){
  48.                 if (notRepeatNumbers){
  49.                     writer.write(firstNumber +  "  и " + secondNumber + "\n");
  50.                     System.out.println(firstNumber +  "  и " + secondNumber);
  51.                     notRepeatNumbers = false;
  52.                 }else{
  53.                     notRepeatNumbers = true;
  54.                 }
  55.             }
  56.         }
  57.         writer.close();
  58.         System.out.println("Информация успешно записана в файл!");
  59.  
  60.     }
  61.  
  62.     public static void main(String[] args) throws Exception {
  63.         System.out.println("Программа выводит все дружественные числа до 32000");
  64.  
  65.         String path = inputPath();
  66.         outputToFile(path);
  67.     }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement