Write a program that lets the user enter 2 numeric values, and an arithmetic operator: +, -, * and /. Write a switch statement that displays the result of the calculation using the operator and two numbers entered by the user.
1 package chapter4; 2 3 import java.util.Scanner; 4 5 public class MathTutor { 6 7 public static void main(String[] args) { 8 9 Scanner scan = new Scanner(System.in); 10 11 int num1, num2; 12 String oper; 13 14 System.out.print("Enter 2 numbers and an an arithmetic operator: +,-,* and / : "); 15 num1 = scan.nextInt(); 16 num2 = scan.nextInt(); 17 oper = scan.next(); 18 19 switch(oper) 20 { 21 22 case "+": 23 System.out.println(num1 + " + " + num2 + " = " + (num1 + num2)); 24 break; 25 26 case "-": 27 System.out.println(num1 + " - " + num2 + " = " + (num1 - num2)); 28 break; 29 30 case "*": 31 System.out.println(num1 + " * " + num2 + " = " + (num1 * num2)); 32 break; 33 34 case "/": 35 System.out.println(num1 + " / " + num2 + " = " + (num1 / num2)); 36 break; 37 38 default: 39 System.out.println("Wrong input!" + oper); 40 41 } 42 43 44 45 46 } 47 48 } 49
No comments:
Post a Comment