Concept explainers
Program plan:
- Import the required packages into the program.
- Create a class Exercise12_01 to throw the NumberFormatException exception.
- In the main() method,
- Declare the required variables.
- Check whether the length of argument is not equal to 3. If yes, display error message.
- In try block, assign the first argument value to variable.
- In catch block, catch the exception if error occurs.
- In try block, assign the third argument value to variable.
- In catch block, catch the exception if error occurs.
- Match the argument 1 with character 0 using switch case.
- If case "+" matches, then add the two numbers and stores the result.
- If case "-" matches, then subtract the two numbers and stores the result.
- If case "." matches, then multiply the two numbers and stores the result.
- If case "/" matches, then divide the two numbers and stores the result.
- Display the result.
The below program demonstrates how to operate mathematical operations and throw a NumberFormatException exception if error occurs.
Explanation of Solution
Program:
Filename: Exercise12_01.java
//Class definition
public class Exercise12_01
{
//Main method
public static void main(String[] args)
{
//Declare and initialize variables
int num1, num2, result = 0;
/*Check whether the length of argument is not equal to 3. */
if (args.length != 3) {
//Display error message
System.out.println("please use java Exercise12_01 operand1 operator operand2");
//Exit the program
System.exit(1);
}
//In try block
try {
//Assign the argument 0 as "num1"
num1 = Integer.parseInt(args[0]);
}
//In catch block
catch (NumberFormatException ex) {
//Display the exception
System.out.println("Wrong Input: " + args[0]);
return;
}
//In try block
try {
//Assign the argument 2 as "num2"
num2 = Integer.parseInt(args[2]);
}
//In catch block
catch (Exception ex) {
//Display the exception
System.out.println("Wrong Input: " + args[2]);
return;
}
//Match the argument 1 with character 0
switch (args[1].charAt(0)) {
//If case "+" matches
case '+':
/*Add the num1 and num2 and stores the result */
result = num1 + num2;
//Break the program
break;
//If case "-" matches
case '-':
/*Subtract the num2 from num1 and stores the result. *
result = num1 - num2;
;
//Break the program
break;
//If case "." matches
case '.':
/*Multiply the num1 with num2 and stores the result */
result = num1 * num2;
;
//Break the program
break;
//If case "/" matches
case '/':
/*Divide the num1 by num2 and stores the result */
result = num1 / num2;
;
}
//Display the calculated result
System.out.println(args[0] + " " + args[1] + " " + args[2] + " = " + result);
}
}
Command to run the program:
java Exercise12_01 4 + 5
4 + 5 = 9
Additional Output:
java Exercise12_01 4 - 5
4 – 5 = -1
java Exercise12_01 4x - 5
Wrong Input: 4x
Want to see more full solutions like this?
Chapter 12 Solutions
Introduction to Java Programming and Data Structures: Brief Version (11th Global Edition)
- (Constructors Throwing Exceptions) Write a program that shows a constructor passing information about constructor failure to an exception handler after a try blockarrow_forwardDirection:Analyze the given problem and create a java program using exception. Problem:Create a program that will accept any real number then,converts the number to fractional number,and multiply the value by 9.arrow_forwardJava Foundations: Please provide a basic exception program. Please use the variables given in the question. Do not use input, output. Thank you. Write the Java code for the following: Write the Java program that reads an integer grade from a user in main( ), then calls the checkGrade method (passing it the grade that was just read in) to check that it is valid (between 0 and 100). if the checkGrade method determines that the grade is invalid, it generates an InvalidGradeException but does not deal with it. the main( ) method deals with the exception by writing a message about the invalid grade.. If the grade is valid, it is written to the monitor.arrow_forward
- Python Code: Write a function that takes a single number as an argument: 1) This function should then check whether a number is an even number (2,4,6,8) and raise an exception if otherwise 2) Call this function with an uneven number first without catching the exception and then with catching the exception and printing a warning to the user afterwards Bonus: Do the same as the above but instead implement your solution for prime numbers and call the function with a non-prime numberarrow_forwardChecked exceptions in Java are those exceptions that are checked at compile time and must be either caught or declared in the method's throws clause. (True/False)arrow_forwardSubject: Object Oriented PrgrammingLanguage: Java ProgramTopic: Exception Define a new exception, called ExceptionLineTooLong, that prints out the error message "The strings is too long". Write a program that reads phrase and throws an exception of type ExceptionLineTooLong in the case where a string is longer than 80 characters. EXAMPLE: Input:The quick brown fox jumped over the lazy dogs. Output:The quick brown fox jumped over the laze dogs. ANOTHER EXAMPLE: Input:The quick brown fox jumped over the lazy dogs. The quick brown fox jumped over the lazy dogs.The quick brown fox jumped over the lazy dogs. The quick brown fox jumped over the lazy dogs.The quick brown fox jumped over the lazy dogs. The quick brown fox jumped over the lazy dogs.The quick brown fox jumped over the lazy dogs. The quick brown fox jumped over the lazy dogs.The quick brown fox jumped over the lazy dogs. The quick brown fox jumped over the lazy dogs.The quick brown fox jumped over the lazy dogs. The quick…arrow_forward
- Java Foundations: Please provide basic exception program. Do not use input, output. Thank you. Write the Java code for the following: Write the Java program that reads an integer grade from a user in main( ), then calls the checkGrade method (passing it the grade that was just read in) to check that it is valid (between 0 and 100). if the checkGrade method determines that the grade is invalid, it generates an InvalidGradeException but does not deal with it. the main( ) method deals with the exception by writing a message about the invalid grade.. If the grade is valid, it is written to the monitor.arrow_forward[Access Control Policy]: A computer system usually implements the exception handling mechanism. Like the interrupt handling mechanism, the original program flow will be stopped until the exception is handled. For example, when a program is calculating c=a/b, and for some reason b was set to 0, the program will encounter the "Division by Zero" exception. The control will be given to the exception handler, and the recovery action could be "report only", "return to the next instruction", "purge the program", etc., based on the severity of the problem. From the abov information, we can conclude: A computer system can integrate both Discretionary Access Control (DAC) and Mandatory Access Control (MAC) security policies An administrator can inhibit the exception handling The exception handling mechanism is like the Mandatory Access Control security policy, no matter which user caused the exception (even the administrator), the program should be stopped, and the control should be given to the…arrow_forward(Throwing Exceptions from a catch) Suppose a program throws an exception and the appropriate exception handler begins executing. Now suppose that the exception handler itself throwsthe same exception. Does this create infinite recursion? Write a program to check your observation.arrow_forward
- Java : Write the code segments in main( ) and in methodA( ) for the following scenario: main( ) passes methodA an int variable called a. methodA generates an exception, but does not deal with it, if a is not between 1 and 100. Hint: main will try and catch the exception and methodA throws exception.arrow_forwardComplete the following tasks: Write an exception handler to catch ValueError and output 'float(): Input is not a float.' Write an exception handler to catch OverflowError and output 'math.pow(): result of 5 raised to the power of ', followed by x_value and ' is too large.'arrow_forwardCalculator.java, is a simple command line calculator.Note that the program terminates if any operand is nonnumeric. Write a program with an exception handler that deals with nonnumeric operands; then write another program without using an exception handler to achieve the same objective. Your program should display a message that informs the user of the wrong operand type before exiting. (See Figure 1)arrow_forward
- Database System ConceptsComputer ScienceISBN:9780078022159Author:Abraham Silberschatz Professor, Henry F. Korth, S. SudarshanPublisher:McGraw-Hill EducationStarting Out with Python (4th Edition)Computer ScienceISBN:9780134444321Author:Tony GaddisPublisher:PEARSONDigital Fundamentals (11th Edition)Computer ScienceISBN:9780132737968Author:Thomas L. FloydPublisher:PEARSON
- C How to Program (8th Edition)Computer ScienceISBN:9780133976892Author:Paul J. Deitel, Harvey DeitelPublisher:PEARSONDatabase Systems: Design, Implementation, & Manag...Computer ScienceISBN:9781337627900Author:Carlos Coronel, Steven MorrisPublisher:Cengage LearningProgrammable Logic ControllersComputer ScienceISBN:9780073373843Author:Frank D. PetruzellaPublisher:McGraw-Hill Education