Advertisement
EBobkunov

division and write result into file

Mar 13th, 2023
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.31 KB | Source Code | 0 0
  1. import java.io.*;
  2.  
  3. public class Main {
  4.     public static void main(String[] args) {
  5.         try(FileInputStream in = new FileInputStream("src\\task1\\input.txt");
  6.             FileOutputStream out = new FileOutputStream("src\\task1\\output.txt"))
  7.         {
  8.             byte[] buffer = new byte[in.available()];
  9.             in.read(buffer, 0, buffer.length);
  10.             System.out.println("Input text: " + new String(buffer));
  11.             //divide text into words
  12.             String[] words = new String(buffer).split(" ");
  13.             //check if only integers
  14.             for (int i = 0; i < words.length; i++) {
  15.                 try {
  16.                     Integer.parseInt(words[i]);
  17.                 } catch (NumberFormatException e) {
  18.                     System.out.println("Not only integers");
  19.                     return;
  20.                 }
  21.             }
  22.             //if number of arguments is not equal two
  23.             if (words.length != 2) {
  24.                 System.out.println("Not two arguments");
  25.                 return;
  26.             }
  27.  
  28.             //convert words to integers
  29.             int[] numbers = new int[words.length];
  30.             //check if the word is a number
  31.             for (int i = 0; i < words.length; i++) {
  32.                 try {
  33.                     numbers[i] = Integer.parseInt(words[i]);
  34.                 } catch (NumberFormatException e) {
  35.                     System.out.println("The word " + words[i] + " is not a number");
  36.                 }
  37.             }
  38.             //check if second number is not zero
  39.             if (numbers[1] == 0) {
  40.                 System.out.println("Division by zero");
  41.             } else {
  42.                 //calculate the result
  43.                 int result = numbers[0] / numbers[1];
  44.                 //write the result to the file
  45.                 out.write(String.valueOf(result).getBytes());
  46.                 System.out.println("Result: " + result);
  47.             }
  48.  
  49.         }
  50.         //input file does not exist
  51.         catch (FileNotFoundException e) {
  52.             System.out.println("File not found");
  53.         }
  54.         //no write-permission for the output file
  55.         catch (IOException e) {
  56.             System.out.println("File can not be written");
  57.         }
  58.         finally {
  59.             System.out.println("Program finished");
  60.         }
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement