Write a program that simulates a simple calculator. The calculator has the abili
ID: 3636143 • Letter: W
Question
Write a program that simulates a simple calculator. The calculator has the ability to have two real numbers inputted and then:*multiply the two numbers
*divide the first number by the second number (be sure to check for division by 0 and provide an error message if this occurs)
*add the two numbers together
*subtract the second number from the first number
Example: User inputs 20 and 5, Output would be:
Multiplied = 100, Divided = 4, Added = 25, Subtracted = 15
Create a method for each of the four tasks. The main method should ask for the numbers and display the results of each of the four tasks. Have the program repeat until the user tells the program to stop.
Explanation / Answer
import java.util.*; public class Calc { public static void main(String[] args) { double a,b; Scanner sc = new Scanner(System.in); while (sc.hasNextDouble()){ a = sc.nextDouble(); b = sc.nextDouble(); if (b == 0){ System.out.println("Can't be divided by zero."); System.out.printf("Multiplied = %d, Divided = NA, Added = %d, Subtracted = %d", multiple(a,b), add(a,b), subtract(a,b)); }else { System.out.printf("Multiplied = %d, Divided = %.2f, Added = %d, Subtracted = %d", multiple(a,b), divide(a,b), add(a,b), subtract(a,b)); } } } public static double multiple(double a,double b){ return a*b; } public static double divide(double a,double b){ return a/b; } public static double add(double a,double b){ return a+b; } public static double subtract(double a,double b){ return a-b; } }
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.