Advertisement
Guest User

Untitled

a guest
Mar 8th, 2016
181
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.38 KB | None | 0 0
  1. package average;
  2. import java.util.Scanner;
  3. import java.io.FileNotFoundException;
  4. import java.lang.SecurityException;
  5. import java.util.Formatter;
  6. import java.util.FormatterClosedException;
  7. import java.util.NoSuchElementException;
  8. import java.util.InputMismatchException;
  9.  
  10.  
  11.  
  12.  
  13. public class Average {
  14.  
  15. private static Formatter output;
  16.  
  17. public static void main(String[] args)
  18. {
  19. openFile();
  20. addRecords();
  21. closeFile();
  22. openFile();
  23. readRecords();
  24. closeFile();
  25. }
  26. public static void openFile()
  27. {
  28. try
  29. {
  30. output = new Formatter("numbers.txt");
  31. }
  32. catch (SecurityException securityException)
  33. {
  34. System.err.println("Write permission denied. Terminating.");
  35. System.exit(1);
  36. }
  37. catch (FileNotFoundException fileNotFoundException)
  38. {
  39. System.err.println("Error opening file. Terminating.");
  40. System.exit(1);
  41. }
  42. }
  43. public static void addRecords()
  44. {
  45. Scanner input = new Scanner(System.in);
  46. System.out.print("Hello, welcome to my program!\n");
  47.  
  48. int[] numbers = new int[10];
  49.  
  50. for (int i = 0 ; i < 10 ; i++) {
  51. System.out.printf("Please enter integer %d: ", i+1);
  52. numbers[i] = input.nextInt();
  53.  
  54. {
  55. try
  56. {
  57. output.format("Inputted integer: %s%n", String.valueOf(numbers[i]));
  58. }
  59. catch (FormatterClosedException formatterClosedexception)
  60. {
  61. System.err.println("Error writing to the file. Terminating.");
  62. break;
  63. }
  64. catch (InputMismatchException inputMismatchException)
  65. {
  66. System.err.println("Please restart the program and enter integers ONLY.");
  67. break;
  68. }
  69. catch (NoSuchElementException elementException)
  70. {
  71. System.err.println("Invalid input. Please try again.");
  72. input.nextLine();
  73. }
  74. //System.out.print("? ");
  75. }
  76. }
  77. }
  78. public static void closeFile()
  79. {
  80. if (output != null)
  81. output.close();
  82. }
  83. public static void readRecords()
  84. {
  85. try
  86. {
  87. while (input.hasNext())
  88. {
  89. System.out.printf("%s%n", String.valueOf(numbers[i]));
  90. }
  91. }
  92.  
  93.  
  94. }
  95. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement