1answer.
Ask question
Login Signup
Ask question
All categories
  • English
  • Mathematics
  • Social Studies
  • Business
  • History
  • Health
  • Geography
  • Biology
  • Physics
  • Chemistry
  • Computers and Technology
  • Arts
  • World Languages
  • Spanish
  • French
  • German
  • Advanced Placement (AP)
  • SAT
  • Medicine
  • Law
  • Engineering
lesantik [10]
4 years ago
9

Write a simple command-line calculator with an exception handler that deals with nonnumeric operands. Your program should displa

y a message that informs the user of the wrong operand type before exiting. It should also ask the user to re-input the number to finish the calculation.

Computers and Technology
1 answer:
alexira [117]4 years ago
8 0

Answer:

Here is the JAVA program:

import java.util.InputMismatchException;  // exception that is thrown when input does not match the expected type

import java.util.Scanner;  //used to take input from user

public class Main {

public static void main(String[] args) { //start of main function

   Scanner input = new Scanner(System.in);  // creates Scanner class object

   double num1=0.0;  // double type operand 1

   double num2=0.0;  // double type operand 2

   System.out.println("Please enter 2 operands");  //prompts user to enter two operands

   try {  //defines a chunk of code to be tested for non numeric operand error

      num1 = input.nextDouble();  //reads operand 1 value

      num2 = input.nextDouble(); //reads operand 2 value

         

   } catch (InputMismatchException  ex) {  //code chunk executed when exception occurs in program

     System.out.println("wrong operand type, re-input " + input.next() + " to finish the calculation.");  //displays wrong operand type if user enters non numeric operands

     System.exit(1);  }//exits the program    

   System.out.print("Enter an operator (+, -, *, /): ");  //prompts user to enter an operator

       char operator = input.next().charAt(0);  //reads the input operator

       double result;  // to store the result of the operation

       switch(operator)         {  //decided operation on basis of input operator

           case '+':  // if user enters + operator

               result = num1 + num2;  //adds two operands

               break;

            case '-':  // if user enters - operator

               result = num1 - num2;  //subtracts two operands

               break;  

           case '*':  // if user enters * operator

               result = num1 * num2;  //multiplies two operands

               break;  

           case '/':  // if user enters / operator

               result = num1 / num2;  //divided two operands

               break;  

           default:  //if user enters wrong operator

               System.out.printf("wrong operator!");  //displays wrong operator

               return;          }  

       System.out.printf("%.1f %c %.1f = %.1f", num1, operator, num2, result); }} //displays the result of the operation

Explanation:

The program is well explained in the comments mentioned with each line of program. The user is prompted to enter the values of two operands num1 and num2. The try block is used to test for non numeric operand error and throws InputMismatchException when any of the input operands (num1 or num2) is non numeric. InputMismatchException is thrown by Scanner class. This informs that the token retrieved (which is the num1 or num2 operand) does not match the expected type (which is type numeric). When this error occurs in the program, catch block is used to execute a code chunk, which is the print statement in this program. The print statement informs the user of the wrong operand type before exiting. It also asks the user to re-input the number to finish the calculation and the wrong input type is also mentioned in the output that is to be re-input.

If you want the program to take the input again from user after throwing this exception then you can alter the above program by using two try catch blocks separately for the two operands:

//for operand 1 i.e. num1

System.out.println("Please enter operand 1: ");

   try {

      num1 = input.nextDouble();        

   } catch (InputMismatchException  ex) {

     System.out.println("wrong operand type, re-input " + input.next() + " to finish the calculation.");

      num1 = input.nextDouble();  }  //reads input of operand 1 again from user

//for operand 2 i.e. num2

          System.out.println("Please enter operand 2: ");  

      try {

      num2 = input.nextDouble();  

   } catch (InputMismatchException  ex) {

     System.out.println("wrong operand type, re-input " + input.next() + " to finish the calculation.");

     num2 = input.nextDouble();  } //reads input of operand 1 again from user

The program and its output is attached.

You might be interested in
Web pages are accessed through a software program called a _____.A) ​web crawlerB) ​web browserC) ​web serverD) ​web app drawer
IrinaVladis [17]

Answer: B) ​web browser

Explanation: A web browser may be explained as a software program or application available on various operating systems such as windows, Mac, Android, iOS among others. This program acts as an interface between information available on websites or pages and users. This application takes a specified uniform resource locator or web address as input and outputs the information available on a web page. Google Chrome, Internet Explorer, Microsoft edge, opera mini, Safari, Firefox and so on.

3 0
3 years ago
Which component of the technological system is achieved when an automobiles airbag inflates
Aleonysh [2.5K]
Process is the component achieved.

8 0
3 years ago
A solid weighs 20gf in air and 18gf in water .find the specific gravity of the solid​
swat32
<h2>Answer:</h2>

10

<h2>Explanation:</h2>

Specific gravity (also called relative density) is the ratio of the density of an object (or substance) to the density of a reference substance (mostly water). It has no unit and is given by the following;

Specific gravity = \frac{density-of-object}{density-of-water}

Specific gravity is also given by the ratio of the weight of the object in air to the loss of weight of the object in water. i.e

Specific gravity = \frac{weight-of-object-in-air}{loss-of-weight-in-water}            --------------(* * *)

In this case;

i. The object is the solid which has a weight of 20gf in air.

ii. The loss of weight of the solid in water is the difference between the weight in air (20gf) and the weight in water (18gf).

Therefore the loss of weight is

20gf - 18gf = 2gf

Now substitute these values from (i) and (ii) into equation (* * *) as follows;

Specific gravity = \frac{20gf}{2gf}

Specific gravity = 10

Therefore the specific gravity of the solid is 10

7 0
3 years ago
Write a program that reads the data from rawdata_2004.txt into a dictionary whose keys are country names and whose values are pe
san4es73 [151]

Answer:

import re

def country_capita():

   #opens file

   file=open("inputfile.txt", "r")

   dictionary=dict()

   #reads line by line

   for line in file.readlines():

       # substitutes for multiple space a single space

       line = re.sub(r"[\s]{2, }", ' ', line)

       list=[]

       #splits line on space

       list=line.split(" ")

       #put into dictionary

       dictionary[list[1]]=list[2]

#   get input

   while True:

       choice=input("Enter the country name or quit to exit: ")

       if choice=="quit":

           break

       elif choice in dictionary.keys():

           print(dictionary[choice])

       else:

           print("Invalid Country")

country_capita()

Explanation:

Using python to code this program. First we, (line 1) import the re module which offers us a set of functions that allows us to search a string for a match. ((line 2) Next we define a function country_capita() that will open rawdata_2004.txt, read the information within line by line and create a dictionary list. The we create a while loop with conditional statements that prompt the user to enter country names, print the corresponding values and stops when the user enters quit.

7 0
3 years ago
Say you are running a program along with many other programs in a modern computer. For some reason, your program runs into a dea
swat32

Answer:

The OS deals with such deadlock to temporarily prevent resources from deadlocked processes. It is either it back off a process to some check point allowing preemption of a needed resource and restarting the process at the checkpoint later. Finally, successively kill processes until the system is deadlock free.

6 0
4 years ago
Other questions:
  • Carl sent an e-mail to more than three thousand employees about a software update. The employees need to prepare for this update
    7·2 answers
  • A system of interlinked documents that are available on the internet is
    5·1 answer
  • What are the main types of software? Explain with appropriate examplesWhat are the main types of software? Explain with appropri
    12·2 answers
  • Given that k refers to an int that is non-negative and that plist1 has been defined to be a list with at least k 1 elements, wri
    14·1 answer
  • What determines the choice of a rocket for a mission?
    11·1 answer
  • Most sim cards allow ___________ access attempts before locking you out.
    10·1 answer
  • A contractor is preparing a bid to install swimming pools at a new housing addition. The estimated time to build the first pool
    12·1 answer
  • Send the memes whoever is the best will get that crown thing lol
    10·2 answers
  • Complete the sentence.
    10·1 answer
  • Jason is playing a game in which players must maneuver around changing barriers
    10·1 answer
Add answer
Login
Not registered? Fast signup
Signup
Login Signup
Ask question!