Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- public class Main {
- public static void main(String[] args) {
- try(FileInputStream in = new FileInputStream("src\\task1\\input.txt");
- FileOutputStream out = new FileOutputStream("src\\task1\\output.txt"))
- {
- byte[] buffer = new byte[in.available()];
- in.read(buffer, 0, buffer.length);
- System.out.println("Input text: " + new String(buffer));
- //divide text into words
- String[] words = new String(buffer).split(" ");
- //check if only integers
- for (int i = 0; i < words.length; i++) {
- try {
- Integer.parseInt(words[i]);
- } catch (NumberFormatException e) {
- System.out.println("Not only integers");
- return;
- }
- }
- //if number of arguments is not equal two
- if (words.length != 2) {
- System.out.println("Not two arguments");
- return;
- }
- //convert words to integers
- int[] numbers = new int[words.length];
- //check if the word is a number
- for (int i = 0; i < words.length; i++) {
- try {
- numbers[i] = Integer.parseInt(words[i]);
- } catch (NumberFormatException e) {
- System.out.println("The word " + words[i] + " is not a number");
- }
- }
- //check if second number is not zero
- if (numbers[1] == 0) {
- System.out.println("Division by zero");
- } else {
- //calculate the result
- int result = numbers[0] / numbers[1];
- //write the result to the file
- out.write(String.valueOf(result).getBytes());
- System.out.println("Result: " + result);
- }
- }
- //input file does not exist
- catch (FileNotFoundException e) {
- System.out.println("File not found");
- }
- //no write-permission for the output file
- catch (IOException e) {
- System.out.println("File can not be written");
- }
- finally {
- System.out.println("Program finished");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement