Answer to Question #308031 in Java | JSP | JSF for Hlo Makiwane

Question #308031

PROGRAM 2 – Maths Calculator


Write a small application in JAVA that reads in two integers, and then asks the user to type in a character to indicate what calculation must be done with the two numbers, viz:


A to add


S to subtract


M to multiply


D to divide


Display the result of the calculation.



The output of sample runs of the program is given below (the text in bold was typed by the user).


Please use the SAME wording/messages/labels as shown.


Sample execution run 1 Sample execution run 2


Enter the first number: 27


Enter the second number: 9



What would you like to do?


A to add


S to subtract


M to multiply


D to divide



Enter choice: s


27 minus 9 is 18.


Enter the first number: 15


Enter the second number: 0



What would you like to do?


A to add


S to subtract


M to multiply


D to divide



Enter choice: D


**Error** Cannot divide by zero.




1
Expert's answer
2022-03-08T13:06:49-0500


import java.util.Scanner;


class App {


	public static void main(String[] args) {
		Scanner keyBoard = new Scanner(System.in);
		System.out.print("Enter the first number: ");
		int number1 = keyBoard.nextInt();
		System.out.print("Enter the second number: ");
		int number2 = keyBoard.nextInt();
		System.out.println("What would you like to do?");
		System.out.println("A to add");
		System.out.println("S to subtract");
		System.out.println("M to multiply");
		System.out.println("D to divide");
		System.out.print("Enter choice: ");
		keyBoard.nextLine();
		char operation = keyBoard.nextLine().toUpperCase().charAt(0);
		double result = 0;
		if (operation == 'A') {
			result = number1 + number2;
			System.out.println(number1 + " plus " + number2 + " is " + result + ".");
		} else if (operation == 'S') {
			result = number1 - number2;
			System.out.println(number1 + " minus " + number2 + " is " + result + ".");
		} else if (operation == 'M') {
			result = number1 * number2;
			System.out.println(number1 + " times " + number2 + " is " + result + ".");
		} else if (operation == 'D') {
			if (number2 != 0) {
				result = number1 / number2;
				System.out.println(number1 + " by " + number2 + " is " + result + ".");
			} else {
				System.out.println("**Error** Cannot divide by zero.");
			}
		} else {
			System.out.println("Wrong operation\n");
		}


		keyBoard.close();
	}
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS