java一个简单的计算器
思路
1.写四个方法,加减乘除
2.利用循环+switch进行用户交互
3.传递需要操作的两个数
4.输出结果
方法一:
package com.wang.method;
import java.util.Scanner;
public class Demo006 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true){
System.out.println("请输入你要执行的命令1.加法2.减法3.乘法4.除法5.退出程序");
int n = scanner.nextInt();
if (n==5){
break;
}
System.out.println("请输入第一个数");
double a = scanner.nextDouble();
System.out.println("请输入第二个数");
double b = scanner.nextDouble();
switch (n){
case 1:
System.out.println(jia(a,b));
break;
case 2:
System.out.println(jian(a,b));
break;
case 3:
System.out.println(cheng(a,b));
break;
case 4:
System.out.println(chu(a,b));
break;
case 5:
System.out.println("程序结束");
break;
}
}
}
public static double jia(double a,double b){
System.out.println("两数之和为:");
return a+b;
}
public static double jian(double a,double b){
System.out.println("两数之差为:");
return a-b;
}public static double cheng(double a,double b){
System.out.println("两数之积为:");
return a*b;
}public static double chu(double a,double b){
System.out.println("两数的商为:");
if(b==0){
System.out.println("错误,o不能做被除数");
}
return a/b;
}
}
方法二:但这个没有循环
package com.wang.method;标签:java,int,double,System,switch,计算器,println,public,out From: https://www.cnblogs.com/wang1999an/p/16748942.html
import java.util.Scanner;
public class Demo0006 {
public static void main(String[] args) {
Scanner st = new Scanner(System.in);
System.out.println("请输入两个数例如(11 + 15)");
//注意,下面定义接收用户输入的三个变量一定要按数字,符号,数字,否则报错
//本人就是写出来了(本人不知道怎么加上去循环),一直没报错,但一运行输入数字结果报错,服了!!!
//还有要注意输入时要注意间隔:a + b
int a = st.nextInt();
char c = st.next().charAt(0);
int b = st.nextInt();
switch (c){
case '+':
test1(a, b);
break;
case '-':
test2(a, b);
break;
case '*':
test3(a, b);
break;
case '/':
test4(a, b);
break;
default:
System.out.println("请输入+-*/");
}
}
private static void test1(int a,int b){
int sum = a + b;
System.out.println("两数之和为:"+sum);
}
public static void test2(int a,int b){
int sum = a - b;
System.out.println("两数之差为:"+sum);
}
public static void test3(int a,int b){
int sum = a * b;
System.out.println("两数的积为:"+sum);
}
public static void test4(int a,int b){
int sum = a / b;
if(b==0){
System.out.println("0不能作为被除数");
}else{
System.out.println("两数商为:"+sum);
}
}
}