写一个计算器,要求实现加减乘除功能,通过用户交互实现
思路:
- 写四个方法
- 利用switch进行用户交互
- 传递需要操作的两个数
- 输出结果
法一:方法没有返回值
package com.zhangyi.base;
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
//创建一个扫描器对象,用于接收
Scanner scanner = new Scanner(System.in);
//从键盘输入数据
System.out.println("请输入一个数:");
double a = scanner.nextDouble();
System.out.println("请输入运算符:");
String symbol = scanner.next();
System.out.println("请输入另一个数:");
double b = scanner.nextDouble();
//switch语句判断运算类型
switch (symbol) {
case "+":
add(a, b);
break;//记得终止
case "-":
subtract(a, b);
break;
case "*":
multiply(a, b);
break;
case "/":
divide(a, b);
break;
}
scanner.close();//关闭scanner资源
}
//加法
public static void add(double a, double b) {
System.out.println("结果是"+(a + b));
}
//减法
public static void subtract(double a, double b) {
System.out.println("结果是"+(a - b));
}
//乘法
public static void multiply(double a, double b) {
System.out.println("结果是"+(a * b));
}
//除法
public static void divide(double a, double b) {
//为了严谨,记得考虑分母为零的情况
if (b == 0) {
System.out.println("分母不能为零!");
} else {
System.out.println("结果是"+(a / b));
}
}
}
法二:方法有返回值
package com.zhangyi.base;
import java.util.Scanner;
public class calculator2 {
public static void main(String[] args) {
//创建一个扫描器对象,用于接收
Scanner scanner = new Scanner(System.in);
//从键盘输入数据
System.out.println("请输入一个数:");
double a = scanner.nextDouble();
System.out.println("请输入运算符:");
String symbol = scanner.next();
System.out.println("请输入另一个数:");
double b = scanner.nextDouble();
switch (symbol) {
case "+":
System.out.println("结果是:" + add(a, b));
break;
case "-":
System.out.println("结果是:" + subtract(a, b));
break;
case "*":
System.out.println("结果是:" + multiply(a, b));
break;
case "/":
if (b == 0) {
System.out.println("分母不能为零!");
} else {
System.out.println("结果是:" + divide(a, b));
}
break;
}
scanner.close();
}
public static double add(double a,double b){
return a+b;
}
public static double subtract(double a,double b){
return a-b;
}
public static double multiply(double a,double b){
return a*b;
}
public static double divide(double a,double b){
return a/b;
}
}
问题:没能够循环接收新的数据
每日分享:
试炼的尽头是花开万里
标签:scanner,double,System,计算器,println,编写,public,out From: https://www.cnblogs.com/zhang11/p/16728332.html