package com.cuit.method; import java.util.Scanner; public class Calculator { public static void main(String[] args) { Calculator calculator = new Calculator(); Scanner scanner = new Scanner(System.in); //for循环和switch实现用户交互 for (int i = 0; i < 100; i++) { System.out.println("1. 加法"); System.out.println("2. 减法"); System.out.println("3. 乘法"); System.out.println("4. 除法"); System.out.println("====================="); System.out.println("第"+(i+1)+"次使用计算器,请选择计算器功能:"); int count = scanner.nextInt(); System.out.println("请输入进行操作的两个数据:"); switch (count){ case 1: { double num1 = scanner.nextDouble(); double num2 = scanner.nextDouble(); System.out.println("加法结果为:"+calculator.add(num1,num2)); break; } case 2: { double num1 = scanner.nextDouble(); double num2 = scanner.nextDouble(); System.out.println("减法结果为:"+calculator.sub(num1,num2)); break; } case 3: { double num1 = scanner.nextDouble(); double num2 = scanner.nextDouble(); System.out.println("乘法结果为:"+calculator.mul(num1,num2)); break; } case 4: { double num1 = scanner.nextDouble(); double num2 = scanner.nextDouble(); System.out.println("除法结果为:"+calculator.div(num1,num2)); break; } default: System.out.println("输入错误,请重新输入"); break; } System.out.println(); } } public double add(double num1,double num2){//加法 return num1+num2; } public double sub(double num1,double num2){//减法 return num1-num2; } public double mul(double num1,double num2){//乘法 return num1*num2; } public double div(double num1,double num2){//除法 return num1/num2; } }
运行结果: