使用Java程序实现计算器的功能
package com.cn.test;
import java.util.Scanner;
public class WriteCalculator {
public double add(double a,double b){
return a+b;
}
public double subduction(double a,double b){
return a-b;
}
public double multiplication(double a,double b){
return a*b;
}
public double division(double a,double b){
return a/b;
}
public static void main(String[] args) {
WriteCalculator wc = new WriteCalculator();
Scanner sc = new Scanner(System.in);
System.out.println("请输入第一个数据:");
double a = sc.nextDouble();
System.out.println("请输入运算符:");
String operator = sc.next();
System.out.println("请输入第二个数据:");
double b = sc.nextDouble();
double result = 0;
sc.close();
if("+".equals(operator)){
result = wc.add(a,b);
}else if ("-".equals(operator)){
result = wc.subduction(a,b);
}else if ("*".equals(operator)){
result = wc.multiplication(a,b);
}else if ("/".equals(operator)){
result = wc.division(a,b);
}
System.out.println("最终输出结果为:"+result);
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("请输入两个数字:");
double a = input.nextDouble();
double b = input.nextDouble();
System.out.print("输入一个运算符 (+, -, *, /): ");
char operator = input.next().charAt(0);
double result = 0;
input.close();
switch (operator){
case '+':
result = a+b;
break;
case '-':
result = a-b;
break;
case '*':
result = a*b;
break;
case '/':
result = a/b;
break;
default:
System.err.print("输入的运算符有误!");
return;
}
System.out.println("最终输出结果为:"+result);
}
}
|