Write a simple command-line calculator with an exception handler that deals with nonnumeric operands. Your program should display 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.

Answers

Answer 1

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.

Write A Simple Command-line Calculator With An Exception Handler That Deals With Nonnumeric Operands.
Write A Simple Command-line Calculator With An Exception Handler That Deals With Nonnumeric Operands.
Write A Simple Command-line Calculator With An Exception Handler That Deals With Nonnumeric Operands.

Related Questions

Which of the following is not a characteristic of data that can strongly affect cluster analysis?
a. Size
b. Spareseness
c. Skewness
d. Scale

Answers

Answer:

c. Skewness

Explanation:

Cluster analysis involves analyzing a set of object by grouping the set of objects in such a way that objects in the one group or cluster are more similar  to each other than to those in other groups or clusters. The characteristics of data that can strongly affect cluster analysis includes the size, sparseness, scale, etc.

Describe the concept of a cursor and how it is used in embedded SQL.

Answers

Answer:

Cursor is the temporary area created when the SQL statement is executed.

Explanation:

Data base management system allows

 Entering Data

 Housekeeping

 Querying data

 Printing reports

Cursor contains the information about the selected statement and the rows data accessed by it. This space is used to store the data retrieve from data base    

A cursor is used to get rows from the query that has many rows in its result sets a cursor is work as a handle and identifier in SQL query. it is very necessary in SQL because it is an object which is used to store the output of query.

A cursor is used to retrieve rows from a query that has multiple rows in its result set. A cursor is a handle or an identifier for the SQL query and a position within the result set.  

Maintenance is an essential task that is often considered to be dull. In information security, penetration testing may be wrongly perceived as being a "hacker-like" activity. In fact, when done correctly, ethical hacking is an important part of risk management. Penetration analysts work under very restrictive rules of engagement when testing systems. This week's project is research on the many ways that penetration analysts limit the risk they pose to internal systems.

Answers

Explanation:

It is important to bear in mind that a penetration tester (analyst) performs a risk management role of a firm's internal system by attempting to break into an IT system.

Here are the benefits to internal systems;

They help detect security loopholes before a cyberattack.They determine how vulnerable a network or computer program is.They advise the IT firm's security teams on how to mitigate vulnerabilities detected.

ANSWER QUICKLY!

Which unit is best for measuring how much data a hard drive can hold?

Terabytes

Byte

Exabytes

Bit

Answers

Answer:

It is bit { measurement used to quantify computer data. }

To print a budget:________.

1. From the Company Center, select Company & Financials > Budgets

2. From the Reports Center, select Budgets & Forecasts > Budget Overview

3. From the Reports Center, select Company & Financials > Budgets

4. From the Reports Center, select Accountant & Taxes > Budgets

Answers

Answer:

The answer is "Option 2".

Explanation:

In the given question, choice 2 is correct because it uses the print a budget in the Quickbooks is used to form the reports in the center, it also selects the budgets and the forecast value is greater than the value of the budget overview, and the wrong choice can be defined as follows:

Choice 1 and Choice 3 both were wrong because it select uses the company and financial value is greater budget value. In choice 4,  It is wrong because it select uses the accountant, and taxes value that is greater budget value.

Compilers translate the instructions written by the programmer into_______code.

Answers

Answer:

object

Explanation:

Which IDS component is essentially the same as a sniffer in that it runs in conjunction with a network card in promiscuous mode? A. Console B. Sensor C. Agent D. Network tap

Answers

Answer:

D. Network tap

Explanation:

A network tap is a hardware device that provides a way to access the data flow across a computer network.

A sniffer is either hardware or software that provides a way to access the data flow across a computer network.

Hence, these two IDS components are very similar.

Cheers.

A network tap is the same as a sniffer in that it runs in conjunction with a network card in promiscuous mode. Therefore, option D is correct.

What is network tap?

A network tap can be described as a system that monitors events on a local network. A tap is a dedicated hardware device, which offers a way to access the data flowing across a network.

The network tap has three ports which are an A port, a B port, and a monitor port. A tap inserted between A and B passes all traffic via unimpeded in real-time, but copies that same data to its monitor port, enabling a third party.

Network taps are generally used for network intrusion detection systems, network probes, packet sniffers, RMON probes, and other monitoring and collection devices and software that need access to a network segment.

Taps are utilized in security applications because they are non-obtrusive, are not detectable on the network, and will pass through or bypass traffic even if the tap stops working.

Learn more about Network tap, here:

https://brainly.com/question/13025421

#SPJ2

Dragging a mouse over text is called ........and ........​

Answers

Answer:

Explanation:

hola friend!!!!

The answer is dragging and dropping

Hope this helps

plz mark as brainliest !!!!!!!!


(I need help also can u guys just give me some example just in case I got confuse)

Answers

Answer:

1) there should be boundaries because you never know what could happen on the internet as people tend to not have control of who is on theyre account or texting them,

2) if you have a phone you should be responsible and not do something that could get you in alot of trouble ,

3) it's important because if somebody else gets your information things can be sent that you didnt send ,that can get you in legal trouble or start a fued between people,

5) comments only matter if you let them matter as people's opinions shouldn't matter to you as long as your happy,

6) block, report , and notify a trusted adult.

How long does it take to wash 12 t-shirts in the quickest way?​

Answers

Answer:

Please let me know also

What do you need to do to deliver a resilient cloud based system that offers your software as a service

Answers

Answer:

Following are the answer to this question:

Explanation:

In this question firstly, it is important to recognize the basics behind its robust cloud-based system, which is the term durability, but also the servers can rapidly retrieve all the information and also that the durable cloud-based framework, which is like the user information has been present, if there is an abrupt failure to any bugs, and although the data are capable of becoming robust. It is the manual that describes it all, so the things reached in other urban centers as well. But when we have a robust cloud-based system in the business so we need to transfer data from the durable system too.

Interpretation is adding meaning to information by making connections and comparisons and by exploring causes and consequences.A. TrueB. False

Answers

Answer:

A. True

Explanation:

When we receive a message from a sender, transmitted in any form of transmission, be it oral, written, by sign, etc. the interpretation is usually left to the receiver to add meaning to the information received. The meaning is added by the receiver by making connections and comparisons, and by exploring causes and consequences. This is why it is critical to consider the age, mental state, social position, and other factors of the receiver before constructing and sending your message.

What is the best way to avoid data loss

Answers

Back up your data.

If you want to avoid data loss, you should back up your data.

(Circumstances) People, constraints, and consumption are some of the key factors that will impact on your critical thinking and shape your ambitions.A. TrueB. False

Answers

Answer:

True

Explanation:

The condition of a society nurtures the level of ambition of individuals in it. For example, the need for advanced technology, demands the need for individuals with programming and inventive skills.

When a high number of people have the need for a product or services and there are constraints to the availability of the much-needed product, an entrepreneur is forced to think critically to provide these services for the purpose of making profit.

What term is used to describe the method external organizations, systems, and "devices use to interact with the blockchain"

Answers

Answer:

Application Programming Interface (API).

Explanation:

Application Programming Interface (API) is a term used to describe the method external organizations, systems, and "devices use to interact with the blockchain."

In Computer programming, an Application Programming Interface (API) can be defined as a software intermediary which primarily allows two (2) software applications to communicate with each other.

Hence, it is a standard set of protocols which defines the type of requests or call a software program makes, how it makes them, accepted data format, programming language used, authentication, encryption etc.

Write an expression to print each price in stock_prices. Sample output with inputs: 34.62 76.30 85.05

Answers

Answer:

Here is the Python program:

stock_prices = input().split() #to take input and splits it into a list

for price in stock_prices: #iterates through stock_prices

   print("$",price) #prints each value of stock_prices with a dollar sign

Explanation:

The program is well explained in the attached comments. I will explain the logic of the program with the help of an example:

Suppose the user enters the following input as stock_prices values

34.62 76.30 85.05

input() method is used to take input from user

split() method is used to split or break this input string and returns a list of strings as:

['34.62', '76.30', '85.05']    

Now the statement for price in stock_prices: iterates through each item of the list and print("$",price) prints each value of list with a dollar sign on the output screen as:

$ 34.62                                                                                                            

$ 76.30                                                                                                            

$ 85.05    

The program inputs the dollar sign to each of the user inputted stick prices. The program written in python 3 goes thus ;

t = input('Enter values : ')

#takes inputs from user for stock prices

stock_prices = [eval(x) for x in t.split()]

#splits the values based on whitespace assigns to a list variable using list comprehension

for price in stock_prices :

#iterates through the prices in the list

print("$", price)

#place the dollar sign behind each value and display

Learn more : https://brainly.com/question/19815377

What do you think is the most important factor affecting the collection of digital data and what impact do you think that this factor has on the ultimate quest for obtaining evidence in a criminal case?

Answers

Answer:

Privacy concerns.

Explanation:

Privacy concerns have played an important role in how we collect digital data. For example, privacy activists believe that an individual has the right to know how his or her information is being used and that such an individual also has the right to withhold such information.

Such issues have affected the ability of law enforcement agencies to investigate criminal activities. For example, an individual who is accused of a crime may claim a right to withhold his personal information, such as his mobile device, and thus he refuses to give out such information.

The most important factor affecting the collection of digital data is privacy.

What is digital data?

Digital data simply means information that's is represented bas discrete symbols. An example is a document that has a string of alphanumeric characters.

In this case, the most important factor affecting the collection of digital data is privacy concerns. It's important for people to know how their information is used.

Learn more about data on:

https://brainly.com/question/25836560

A general rule for printing is to use _____ fonts for headlines and serif fonts for body text

Answers

Answer:

Times Roman

Explanation:

A qualifier distinguishes the set of objects at the far end of the association based on the qualifier value.
A. True
B. False

Answers

Answer:

True

Explanation: A qualifier is a term used in IT(information technology) and computer software. It is used to differentiate/ identify and select different sets of objects that are located at the far ends of a qualifier association.

A qualifier is usually used to identify an object from a set of closely related and similar objects, they are usually small boxes possibly with a rectangular shape.

Why computer is known as data processing system?

Answers

Explanation:

Hey, there!!

Computer is known as data processing system because when the user input raw data in computer for performing any task it takes them starts to process it according to the instructions given by user. And produce a meaningful information. So, the reason to call it as a data processing system is it process the raw data.

Hope it helps...

Answer:

A computer is known as a data processor because it changes raw data that is not in useful form such as tables, figures etc into processed data known as information that is useful. Processing includes manipulating, storing, accessing and transmitting.

I What are the three major types of equity accounts? The three major types of equity accounts are investments, ________________ , and retained earnings.

Answers

Answer:

Equity accounts include common stock, paid-in capital, and retained earnings. The type and captions used for equity accounts are dependent on the type of entity.

Creating a new name with typedef __________.creates a new typecreates a new type namecreates a new variable namecreates a new variable

Answers

Answer:-

The typedef specifier cannot be combined with any other specifier except for type-specifiers. The typedef-names are aliases for existing types, and are not declarations of new types. Typedef cannot be used to change the meaning of an existing type name (including a typedef-name).

NAME THE DIGITAL MEDIA DEVICE THAT REPLACED BY THESE ANALOG DEVICES. PHONOGRAPH/RECORD PLAYER= software, digital images, digital video, video games, MOVIE FILM=

Answers

Answer:

Digital video?

Explanation:

Most of old analog tech was wiped out because of DIgital video.

but you put this in a weird context

The following system is ideal for representing large, sparsely-populated tables that have a need for real-time, read-write random access.
A. Hadoop
B. MS SQL Server
C. HBase
D. Hive

Answers

Answer:

The correct answer is C. HBase.

Explanation:

HBase is a database system written in the Java programming language. It is open-source and can store enormous amounts of data in tables in billions of rows and columns. It enables random read and write operations in real time. In HBase, the query fetch time is less. It is designed to store denormalized data in wide and sparsely populated tables in contrast to the relational database management system.

Which is an example of correct HTML?
<h1>This is a heading </h1>
</h1>This is a heading<h2>
</h1>This is a title</h1>
<p/>This is a title</p>
please help! god bless you all

Answers

Answer: The first option

Explanation: In HTML, tags are used to classify the format of text between them. The correct usage of a tag is shown in the first option, with the first tag, <h1>, proclaiming that the following text is a part of the first header (hence h1), and the second tag proclaiming the conclusion of the first (the forward slash before the h1 in the second tag shows that the first tag is being concluded, and no text past that point pertains to the tags).

Answer:

a is the answer i took same quiz

Explanation:

For users at home, which file sharing is most likely the simplest to set up and use?
A. Any folder sharing.
B. Public folder sharing.
C. Homegroup sharingd.
D. None of the above.

Answers

Answer:

C. Homegroup sharing

Explanation:

Homegroup sharing:

The type of sharing method you choose to use depends on the size and formality of the network to which the computer is connected. For home users, homegroup networking is simple to set up and use.

While for small business networkers, Public folder sharing is often the easiest method, one that users can easily maintain for themselves on a day-to-day ( daily ) basis.

For larger networks, Windows domain networks, or any network with more elaborate security requirements, any folder sharing is preferable.

How can computers contribute toward creating a "paperless society"? (check all that apply)
A.by making it easier to print copies for archival purposes
B.by using LMS online programs in primary and secondary education
C. by increasing the scope and type of input devices
D. by making information available online to a larger number of people

Answers

the answers are:

- (b) by using LMS online programs in primary and secondary education.

- (c) by increasing the scope and type of input devices.

- (d) by making information available online to a larger number of people.

By using LMS online programs in primary and secondary education and by making information available online to a larger number of people. Therefore, the correct answers are options B and D.

The two main ways that computers can contribute towards creating a paperless society is by using Learning Management Systems (LMS) online programs in primary and secondary education and by making information available online to a larger number of people. By making information available online, people are able to access data from anywhere, reducing the need to use paper and physical documents. LMS programs also help reduce the need for paper and physical documents by allowing students and teachers to manage, store, and distribute content electronically. In addition, these systems enable teachers to give exams and assign projects with fewer physical resources. These methods reduce paper waste and increase efficiency.

Therefore, the correct answers are options B and D.

Learn more about the paperless society here:

https://brainly.com/question/601839.

#SPJ2

According to Nagrin, what are the four roles that video can play?

Answers

Answer:

4 Types of Play

Functional Play. Functional play is playing simply to enjoy the experience.

Constructive Play. As the name suggests, this play involves constructing something (building, drawing, crafting, etc.).

Exploratory Play. During exploratory play, a child examines something closely in order to learn more about it.

Dramatic Play.

You are doing a Diffie-Hellman-Merkle key exchange with Steve using generator 2 and prime 23. You pick the secret number 10. What value will you send to Steve

Answers

Answer:

12

Explanation:

Given:

Generator = g = 2

Prime = p = 23

secret number = a = 10

To find:

Let A be the value to be sent to Steve

Solution:

A = gᵃ mod p

  = 2¹⁰ mod 23

  = 1024 mod 23

  = 12

A = 12

Hence the value sent to Steve is 12

After reading a security bulletin, a network security manager is concerned that a malicious actor may have breached the network using the same software flaw The exploit code is publicly available and has been reported as being used against other industries in the same vertical Which of the following should the network security manager consult FIRST to determine a priority list for forensic review?

Answers

Answer:

C

Explanation:

Other Questions
The product of two irrational numbers isrational. 3x-30 =1.5 plz help me When a firm develops a knowledge asset, such as a process, pays for it and reuses it over and over at a very low cost, this adds ___________ for the firm. Melody is riding her mountain bike along a trail with multiple hills. At the bottom of the second hill, she has 3200 J of kinetic energy. At the top of the third hill, when she is going the slowest, her potential energy measures 1650 J. Which statement below is true? A. The total amount of energy at the bottom of the hill cannot equal the amount at the top, because some of the energy from the environment is gained. B. The total amount of energy at the top is equal to the amount at the bottowm, but she gained some energy as she traveled due to a higher speed going down the first two hills. C. The total amount of energy at the bottom of the hill cannot be equal to the amount at the top, because some of the energy is lost. What statement is true of all living organisms? A 2000 kilogram sports car accelerates at a ratr of 30 meters per second squared. The velocity of the car is v=at where a is acceleration in meters per second squaref and t is tome in seconds. The kinetic energy of the car is KE = 1/2 mv^2 A research company wants to test the claim that a new multi vitamin helps improve short term memory state the objective of the experiment suggest a population determine the experimental and control groups and describe a simple procedure Which of the following lists is ordered from least to greatest? 1.5, 2, 0, , 2, 1.5, 0, , |1.5|, 2, 0, , 2, 1.5, 0, , 50 PTS WILL GIVE BRAINLIEST TO FIRST CORRECT ANSWER!! Why do you think it might be important to try to empathize with others? How far is a chord of length 8 cm from the centre of a circle of radius 5 cm please help// geometry question.... the distance from is cut off from the picture Solve the following and round to the nearest thousandth.0.25 (7.5) what does i never fell flat mean? Choose ALL of the statements below that are stated as a hypothesis.The brighter the color of an orange, the juicler the fruitThe faster a river flows, the greater the erosion.Most apples are red, but some are yellow.Baking powder is used in biscuits.Brass contains copper and zinc. 5. OSHA ensures that employees have the right to:A) O Take 30-minute lunch breaksB) Receive information and training on workplace hazardsC) A designated parking spaceDO A clean uniform During a recent fiscal year, Creek Company reported pretax income of $123,000, a contribution margin ratio of 25% and total contribution margin of $380,000. Total variable costs must have been:_________. a. $1028,000 b. $1,140,000 c. $492,000 d. $1,520,000 $2,012,000 It ___ (rain) (use present continuos tense) What is 10a - 5b if a = 25 and b = 3 2 Which detail best supports the idea that the Brooklyn Bridge helped create modern-day New York City? A.The bridge had the support of civic leaders in Brooklyn. B.The bridge helped ease overcrowding in New York. .The Brooklyn Bridge successfully linked what had been two independent cities, Brooklyn and New York. D. John A. Roebling designed the Brooklyn Bridge to make travel easier between New York and Brooklyn. What is one way that the Choctaw adapted to life out west