Advertisement
Aldin-SXR

Main.java

Feb 27th, 2020
329
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.45 KB | None | 0 0
  1. package ds.intro;
  2.  
  3. import java.io.File;
  4. import java.io.FileNotFoundException;
  5. import java.io.FileWriter;
  6. import java.io.IOException;
  7. import java.util.Scanner;
  8.  
  9. public class Main {
  10.  
  11.     public static void main(String[] args) throws IOException {
  12.         System.out.println("Reading numbers...");
  13.         int[] numbers = MaxInteger.readNumbers("/home/aldin-sxr/numbers.txt");
  14.         int maxNumber = MaxInteger.findMax(numbers);
  15.         System.out.println("Maximum number is: " + maxNumber);
  16.         System.out.println("Writing to file...");
  17.         MaxInteger.writeToFile("/home/aldin-sxr/maxNumber.txt", maxNumber);
  18.     }
  19.    
  20.     /* Read the integer list from a file in the given path */
  21.     public static int[] readNumbers(String path) throws FileNotFoundException {
  22.         int[] numbers = new int[100];
  23.         Scanner scanner = new Scanner(new File(path));
  24.         int i = 0; // counter
  25.         while (scanner.hasNextLine()) {
  26.             numbers[i] = Integer.parseInt(scanner.nextLine());
  27.             i++;
  28.         }
  29.         scanner.close();
  30.         return numbers;
  31.     }
  32.    
  33.     /* Find the maximum integer */
  34.     public static int findMax(int[] numbers) {
  35.         int max = numbers[0];
  36.         for (int i = 1; i < numbers.length; i++) {
  37.             if (numbers[i] > max) {
  38.                 max = numbers[i];
  39.             }
  40.         }
  41.         return max;
  42.     }
  43.    
  44.     /* Write the maximum number to a file */
  45.     public static void writeToFile(String path, int maxNumber) throws IOException {
  46.         File file = new File(path);
  47.         FileWriter fw = new FileWriter(file);
  48.         fw.write(Integer.toString(maxNumber));
  49.         fw.close();
  50.     }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement