Answered step by step
Verified Expert Solution
Question
1 Approved Answer
Writing Methods that Return a Value Summary In this lab, you complete a partially written Java program that includes a method that returns a value.
Writing Methods that Return a Value
Summary
In this lab, you complete a partially written Java program that includes a method that returns a value. The program is a simple calculator that prompts the user for two numbers and an operator ( +, , *, /,or% ). The two numbers and the operator are passed to the method where the appropriate arithmetic operation is performed. The result is then returned to the main() method where the arithmetic operation and result are displayed. For example, if the user enters 3, 4, and *, the following is displayed:
3.00 * 4.00 = 12.00
// Calculator.java - This program performs arithmetic, ( +. -, *. /, % ) on two numbers. // Input: Interactive. // Output: Result of arithmetic operation import java.util.Scanner; public class Calculator { public static void main(String args[]) { double numberOne, numberTwo; String numberOneString, numberTwoString; String operation; double result; Scanner input = new Scanner(System.in); System.out.println("Enter the first number: "); numberOneString = input.nextLine(); numberOne = Double.parseDouble(numberOneString); System.out.println("Enter the second number: "); numberTwoString = input.nextLine(); numberTwo = Double.parseDouble(numberTwoString); System.out.println("Enter an operator (+.-.*,/,%): "); // Call performOperation method here result = performOperation(numberOne, numberTwo, operation); System.out.format("%.2f",numberOne); System.out.print(" " + operation + " "); System.out.format("%.2f", numberTwo); System.out.print(" = "); System.out.format("%.2f", result); System.exit(0); } // End of main() method. // Write performOperation method here. public static double performOperation(double numOne, double numTwo, String oper) { double result = 0; if(oper.equals("+")) result = numOne + numTwo; else if(oper.equals("-")) result = numOne - numTwo; else if(oper.equals("*")) result = numOne * numTwo; else if(oper.equals("/")) if(numTwo == 0) System.out.println("Division by 0 not allowed."); else result = numOne / numTwo; else if(oper.equals("%")) result = numOne % numTwo; else System.out.println("Error. Not a valid operator."); return(result); } // End of performOperation method } // End of Calculator class.
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started