+1 (315) 557-6473 

Java Program to Implement Use of Exceptions Assignment Solution.


Instructions

Objective
Write a program to implement use of exceptions in java.

Requirements and Specifications

Assignment: Write a java assignment program to practice with the use of exceptions and text files.
Constraints:
  • Do not use break/continue in your loops. Do not use the System.exit() method to exit the program.
  • Do not use global variables. The only global variable allowed would be the definition of the Scanner class, or in very specific situations as strictly required by the program requirements.
  • Write a method that returns a valid integer. The function does not have a parameter. In our case, a valid integer is any whole number. Use the try/catch statements to handle the error in data entry. Using a loop, make sure to ask the user for a valid integer.
  • Write a method to provide a menu of options. Make sure to call the method in step 0 (above) to get an integer for the menu choice.
  • Write a method that returns a valid decimal number. In our case a valid decimal number is any number between 1 and 100. For example, 3.8, 90, and 2.789 are all valid input. Use the try/catch statements to handle the error in data entry. Using a loop, make sure to ask the user for a valid number.
  • Write a method to perform the following tasks. The method does not return a value and does not have any parameters.
    • Create an array with 10 random integers between 10 and 100, inclusive.
    • Display the content of the array.
    • Prompt the user to enter an index number of the array and display the
    • corresponding element value. If the specified index is out of bounds, handle the exception and display the message out of bounds. HINT:
IndexOutOfBoundsException will catch such errors. For example, if the user enters -1 or 12 for array index value, an exception must be thrown.
  • Ask the user for the name of an output file. Write your own full name (do not ask for input) as the first line of the file and write the contents of this array to this file.
Write a method to perform the following tasks:
  • I have provided a text file named testData.txt. It contains a string of characters. You can also test your code with the attached file of the book “pride and prejudice” (pride_and_prejudice.txt). Write code to verify if the file exists using try/catch block. If the file exists, calculate, and display the number of vowels (a, e, i, o, u – case insensitive), the number of digits in the file., and the size of the file in bytes. Hard-code the name of the file as textData.txt. If the file does not exist, display an error message. “hard-code” simply means to assign the name of the file as the constant “testData.txt”.
  • NOTE: Simply download the file into your local folder where your source file exists in order to use it for your testing.
Write a main method that tests the functionality of these methods. Make sure to display the data to properly test your code. See the sample interaction for an example.
Source Code
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
import java.util.Scanner;
public class App {
private static Scanner sc;
/** QUESTION 0 */
/**
* Method that returns a valid integer inputted from user
* @return int
*/
public static int getInteger() {
int number;
while(true) {
try {
number = Integer.valueOf(sc.nextLine());
return number;
}
catch(Exception ex) {
// If we get an exception, it is because the user entered an non-numeric value
System.out.println("*** Invalid entry - Try again");
}
}
}
/** QUESTION 2 */
/**
* Method that returns a valid decimal in the range [1,100] inputted from user
* @return double
*/
public static double getDecimal() {
double number;
while(true) {
try {
number = Double.valueOf(sc.nextLine());
if(number >= 1 && number <= 100) {
return number;
} else {
System.out.println("*** Invalid entry - Try again");
}
}
catch(Exception ex) {
// If we get an exception, it is because the user entered an non-numeric value
System.out.println("*** Invalid entry - Try again");
}
}
}
/** QUESTION 3 */
/**
* This function creates an array with 10 random integers between 10 and 100.
* It then displays the array and ask user for an index to display an specific element
*/
static void arrayMethod() {
// First, create the array
int[] array = new int[10];
// Create random object
Random rand = new Random();
// Fill array with random integers
for(int i = 0; i < 10; i++) {
array[i] = rand.nextInt(100) + 1;
}
// Display array
System.out.println("Array data:");
for(int i = 0; i < 10; i++) {
System.out.print(array[i] + " ");
}
System.out.print("\n");
// Ask user for index
int index;
System.out.print("Enter a index of the array: ");
index = getInteger();
if(index >= 0 && index < 10) {
// Display element at given index
System.out.println(String.format("The index %d has %d stored.", index, array[index]));
} else {
System.out.println("Error, invalid index was entered.");
}
// Ask for filename
String out_name;
System.out.print("Enter a filename to save array: ");
out_name = sc.nextLine();
// Write array to file
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(out_name));
for(int i = 0; i < 10; i++) {
writer.write(array[i] + " ");
}
writer.close();
} catch(IOException ex) {
System.out.println("Could not save to file " + out_name + ".");
}
}
/** QUESTION 4 */
static void analizeFile() {
// Declare the filename
String filename = "pride_and_prejudice.txt";
// Declare variables to store number of vowels, digits and size in bytes
int vowels = 0;
int digits = 0;
long bytes = 0;
// Now, try open the file
String line;
try {
BufferedReader reader = new BufferedReader(new FileReader(filename));
// read lines in file
while((line = reader.readLine()) != null) {
// Now, analyze line
// Loop through each character in the line
for(int i = 0; i < line.length(); i++) {
char c = line.charAt(i);
// Get ASCII id of current character
int ci = (int)c;
// If the character index is between [65,90] or [97,122] then it is a vowel
if((ci >= 65 && ci <= 90) || (ci >= 97 && ci <= 122)) {
vowels++;
} else if(ci >= 48 && ci <= 57) {
// If the char index is between [48,57] the it is a digit
digits++;
}
}
}
// Now, get the size in bytes
bytes = new File(filename).length();
// Print info
System.out.println("Number of vowels: " + vowels);
System.out.println("Number of Digits: " + digits);
System.out.println("The file has " + bytes + " bytes");
// Close reader
reader.close();
} catch(IOException ex) {
// If we get a IO exception it is because the file could not be read
System.out.println("Could not open the file 'pride_and_prejudice.txt");
ex.printStackTrace();
}
}
/** QUESTION 1 */
/**
* This function displays the menu to user
*/
static void menu() {
System.out.println("Enter 1 to validate an integer");
System.out.println("Enter 2 to validate a decimal number");
System.out.println("Enter 3 to process an array");
System.out.println("Enter 4 to process a file");
System.out.println("Enter 5 to exit");
}
public static void main(String[] args) {
int option, integer;
double decimal;
// Initialize scanner
sc = new Scanner(System.in);
// Display menu
boolean running = true;
while(running) {
// Display menu
menu();
// Get menu option
option = getInteger();
if(option == 1) {
// Product of two integers
System.out.print("Enter an integer to test, more than -5: ");
integer = getInteger();
if(integer > -5) {
System.out.println(String.format("You entered a valid integer: %d", integer));
} else {
System.out.println("Invalid integer.");
}
} else if(option == 2) {
// Sum of two decimals
System.out.print("Enter a decimal number: ");
decimal = getDecimal();
System.out.println(String.format("You entered a valid decimal number: %.1f", decimal));
} else if(option == 3) {
// Array method
arrayMethod();
} else if(option == 4) {
// analize file
analizeFile();
} else if(option == 5) {
// Exit
running = false;
}
}
System.out.println("");
}