I\'ve asked this once before, but the program will not compile, an error in the
ID: 3917574 • Letter: I
Question
I've asked this once before, but the program will not compile, an error in the scanner line
IN Java GUI
Objective: Utilize try-catch statements in a Java program to catch an ArithmeticException and anInputMismatchException.
The Problem
The program must use OOP style and have more than one class containing methods.
The program must at some point ask the user for the input of numbers.
There must be methods to handle the input of the numbers to insure that type mismatches should not crash the program.
The program must do at least one calculation. If it is possible to have a division by zero, there should be atry-catch to catch it and prevent the program from crashing.
There must be at least one try-catch statement in your program.
1. Before You Begin
2. The Assignment
2.1. Specifications
2.2. General
Use good comments in the body of the program.
Think about the problem and decide what type each of the input numbers should be. Also, think about the calculations and decide what type the variables should be that will hold the results of the calculations.
Use camel casing for variable names, and use descriptive variable names. Do not use general variable names like "tax" or "total."
Take a look at the method below.
This method will cause the program to crash.
Example 1: A method that tries to perform an impossible task
Here is another example of a method that asks for an int and displays the number entered.
A good way to handle a situation like this is to have a method (think one task) that will return an int from the user, but will continue to ask for input until an int is received. This would prevent a type mismatch and cause the program to end.
You could use this method any time you needed an int from the user. You might also create a method for doubles as well.
You would not put the prompting in the method because the prompting would be different in each program.
Example 2: A method that will return an int.
You will have a good bit of leeway in completing this problem.You may create any problem you like, as long as it meets the specifics below. It can be written to display the results in the terminal, or it can be written in GUI style.
Explanation / Answer
Here is the completed code for this problem. The working of this example is provided in the comments, go through it, learn how things work and let me know if you have any doubts. Thanks
// Operations.java
import java.util.Scanner;
/**
* This class is used to perform some operations in an integer array.
* Functionalities include adding integers to the array, finding the average of
* odd numbers and average of even numbers.
*
*/
public class Operations {
private int[] array; // integer array to store numbers
private int count;// current number of elements
private int CAPACITY = 20; // capacity of array
private Scanner scanner; // to read user input
/**
* constructor to initialize the object
*/
public Operations() {
// initializing array, count and scanner
array = new int[CAPACITY];
count = 0;
scanner = new Scanner(System.in);
}
/**
* method to prompt the user and add a number to the array
*/
public void addNum() {
if (count < array.length) {
System.out.print("Enter an integer: ");
// here, there is a chance to cause an Exception
int num = scanner.nextInt();
array[count] = num;
count++;
}
}
/**
* method to find and return the average of odd numbers in the list
*
* @return the average as double value
*/
public double averageOfOddNumbers() {
double avg = 0;
int sum = 0;
int oddCount = 0; // count of odd numbers
for (int i = 0; i < count; i++) {
if (array[i] % 2 != 0) {
// finding the sum and count of odd numbers
oddCount++;
sum += array[i];
}
}
// here, there is a chance to cause Exception if the oddCount is 0
avg = sum / oddCount;
return avg;
}
/**
* similar method as above, except that this method will return the average
* of even numbers
*/
public double averageOfEvenNumbers() {
double avg = 0;
int sum = 0;
int evenCount = 0;
for (int i = 0; i < count; i++) {
if (array[i] % 2 == 0) {
evenCount++;
sum += array[i];
}
}
avg = sum / evenCount;
return avg;
}
/**
* method to prompt the user to make a choice and return the choice
*
* @return integer representing the choice
*/
public int showMenuAndGetChoice() {
System.out.println("1. Add an integer to the list");
System.out.println("2. Find the average of odd numbers in the list");
System.out.println("3. Find the average of even numbers in the list");
System.out.println("4. Quit");
System.out.print("Enter your choice: ");
int choice = scanner.nextInt();
return choice;
}
/**
* method to clear the next line character from scanner in case of any
* excepions occured during nextInt() call
*/
public void clearBuffer() {
scanner.nextLine();
}
}
// ExceptionDemo.java (class with main method)
import java.util.InputMismatchException;
/**
* This is a driver class with a main method and try catch block to perform
* operations on Operations object
*
*/
public class ExceptionDemo {
public static void main(String[] args) {
/**
* creating an Operations object
*/
Operations operations = new Operations();
int choice = 0;
/**
* looping until user chooses to quit
*/
while (choice != 4) {
try {
// getting choice
choice = operations.showMenuAndGetChoice();
// performing actions based on choice
switch (choice) {
case 1:
operations.addNum();
break;
case 2:
System.out.println("Average of odd numbers: "
+ operations.averageOfOddNumbers());
break;
case 3:
System.out.println("Average of even numbers: "
+ operations.averageOfEvenNumbers());
break;
case 4:
System.out.println("Bye!");
break;
default:
System.out.println("Invalid choice");
break;
}
} catch (ArithmeticException e) {
/**
* An ArithmeticException occured. This happens when you call
* averageOfOddNumbers() when there is no odd numbers on the
* list (division by zero), or averageOfEvenNumbers() when there
* is no even number
*/
System.out.println("Division by zero occured!");
} catch (InputMismatchException e) {
/**
* Happens when user input a non integer when prompted to enter
* an integer
*/
System.out.println("Invalid input given!");
//clearing next line character to avoid infinite loop
operations.clearBuffer();
}
}
}
}
/*OUTPUT*/
1. Add an integer to the list
2. Find the average of odd numbers in the list
3. Find the average of even numbers in the list
4. Quit
Enter your choice: 1
Enter an integer: 100
1. Add an integer to the list
2. Find the average of odd numbers in the list
3. Find the average of even numbers in the list
4. Quit
Enter your choice: 2
Division by zero occured!
1. Add an integer to the list
2. Find the average of odd numbers in the list
3. Find the average of even numbers in the list
4. Quit
Enter your choice: 1
Enter an integer: 102
1. Add an integer to the list
2. Find the average of odd numbers in the list
3. Find the average of even numbers in the list
4. Quit
Enter your choice: 3
Average of even numbers: 101.0
1. Add an integer to the list
2. Find the average of odd numbers in the list
3. Find the average of even numbers in the list
4. Quit
Enter your choice: 1
Enter an integer: 101
1. Add an integer to the list
2. Find the average of odd numbers in the list
3. Find the average of even numbers in the list
4. Quit
Enter your choice: 2
Average of odd numbers: 101.0
1. Add an integer to the list
2. Find the average of odd numbers in the list
3. Find the average of even numbers in the list
4. Quit
Enter your choice: x
Invalid input given!
1. Add an integer to the list
2. Find the average of odd numbers in the list
3. Find the average of even numbers in the list
4. Quit
Enter your choice: 1
Enter an integer: c
Invalid input given!
1. Add an integer to the list
2. Find the average of odd numbers in the list
3. Find the average of even numbers in the list
4. Quit
Enter your choice: 4
Bye!